0
0
Reactframework~30 mins

Why conditional rendering is needed in React - See It in Action

Choose your learning style9 modes available
Why Conditional Rendering is Needed in React
📖 Scenario: Imagine you are building a simple React app that shows a welcome message only when a user is logged in. If the user is not logged in, the app should show a login prompt instead. This is a common real-world situation where you want to show different things on the screen based on some condition.
🎯 Goal: Build a React component that uses conditional rendering to show either a welcome message or a login prompt depending on whether the user is logged in.
📋 What You'll Learn
Create a state variable to track if the user is logged in
Create a configuration variable for the welcome message
Use conditional rendering to show the welcome message only when the user is logged in
Show a login prompt when the user is not logged in
💡 Why This Matters
🌍 Real World
Conditional rendering is essential in React apps to show or hide parts of the UI based on user actions or data, like login status, permissions, or feature flags.
💼 Career
Understanding conditional rendering is a fundamental skill for React developers, enabling them to build dynamic and responsive user interfaces.
Progress0 / 4 steps
1
DATA SETUP: Create a state variable for login status
In a React functional component, create a state variable called isLoggedIn using useState and set its initial value to false.
React
Need a hint?

Use const [isLoggedIn, setIsLoggedIn] = useState(false); inside the component.

2
CONFIGURATION: Add a welcome message variable
Inside the WelcomeApp component, create a constant called welcomeMessage and set it to the string 'Welcome back, user!'.
React
Need a hint?

Use const welcomeMessage = 'Welcome back, user!'; inside the component.

3
CORE LOGIC: Use conditional rendering to show messages
Inside the WelcomeApp component, return JSX that uses a conditional expression with isLoggedIn to show a <h1> with welcomeMessage if isLoggedIn is true, or a <p> with the text 'Please log in.' if false.
React
Need a hint?

Use a ternary operator inside JSX: {isLoggedIn ? <h1>{welcomeMessage}</h1> : <p>Please log in.</p>}

4
COMPLETION: Add a button to toggle login status
Add a <button> inside the returned JSX that toggles isLoggedIn between true and false when clicked. The button text should be 'Log out' if isLoggedIn is true, or 'Log in' if false.
React
Need a hint?

Add a button with an onClick handler that calls setIsLoggedIn(!isLoggedIn) and shows text based on isLoggedIn.