0
0
Reactframework~30 mins

If conditions in JSX in React - Mini Project: Build & Apply

Choose your learning style9 modes available
If conditions in JSX
📖 Scenario: You are building a simple React component that shows a greeting message. Sometimes the user is logged in, and sometimes not. You want to show a special message only when the user is logged in.
🎯 Goal: Create a React functional component that uses an if condition inside JSX to show a welcome message only if the user is logged in.
📋 What You'll Learn
Create a boolean variable called isLoggedIn with the value true.
Create a string variable called userName with the value 'Alice'.
Use an if condition inside the JSX to show Welcome, Alice! only if isLoggedIn is true.
If isLoggedIn is false, show Please log in. instead.
💡 Why This Matters
🌍 Real World
Showing different content based on user login status is very common in websites and apps.
💼 Career
Understanding conditional rendering in React is essential for building interactive user interfaces.
Progress0 / 4 steps
1
Set up user login state variables
Create a boolean variable called isLoggedIn and set it to true. Also create a string variable called userName and set it to 'Alice' inside the Greeting component.
React
Need a hint?

Use const to create variables inside the component function.

2
Add a helper variable for the greeting message
Create a variable called message that will hold the greeting text. Initialize it as an empty string '' inside the Greeting component, below the isLoggedIn and userName variables.
React
Need a hint?

Use let because you will change the value later.

3
Use an if condition to set the message
Use an if statement to check if isLoggedIn is true. If yes, set message to `Welcome, ${userName}!`. Otherwise, set message to 'Please log in.'.
React
Need a hint?

Use backticks ` for the template string with ${userName}.

4
Render the message inside JSX
Inside the return statement, replace the comment with JSX that displays the message variable inside a <p> tag.
React
Need a hint?

Use curly braces {} to insert the variable inside JSX.