0
0
Reactframework~30 mins

Conditional component rendering in React - Mini Project: Build & Apply

Choose your learning style9 modes available
Conditional component rendering
📖 Scenario: You are building a simple React app that shows a greeting message only if the user is logged in.
🎯 Goal: Create a React component that conditionally renders a greeting message based on a login status.
📋 What You'll Learn
Create a state variable to track if the user is logged in
Create a boolean variable to represent the login status
Use conditional rendering to show a greeting message only when logged in
Render a button to toggle the login status
💡 Why This Matters
🌍 Real World
Conditional rendering is common in apps to show or hide parts of the UI based on user actions or data, like showing login status or notifications.
💼 Career
Understanding conditional rendering is essential for React developers to build dynamic and interactive user interfaces.
Progress0 / 4 steps
1
Set up the initial React component and state
Create a React functional component called Greeting. Inside it, use the useState hook to create a state variable called isLoggedIn and set its initial value to false.
React
Need a hint?

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

2
Add a button to toggle login status
Inside the Greeting component, add a button element. Set its onClick handler to toggle the isLoggedIn state between true and false using setIsLoggedIn.
React
Need a hint?

Use <button onClick={() => setIsLoggedIn(!isLoggedIn)}> to toggle the login state.

3
Add conditional rendering for the greeting message
Inside the Greeting component's return, add a conditional rendering that shows a <p> element with the text "Welcome back!" only if isLoggedIn is true. Keep the toggle button visible always.
React
Need a hint?

Use {isLoggedIn && <p>Welcome back!</p>} inside the return.

4
Add accessibility and semantic improvements
Wrap the button and greeting message inside a <section> element. Add an aria-live="polite" attribute to the <p> greeting message to announce changes to screen readers.
React
Need a hint?

Wrap the content in <section> and add aria-live="polite" to the greeting paragraph.