0
0
Reactframework~30 mins

Ternary operator usage in React - Mini Project: Build & Apply

Choose your learning style9 modes available
Ternary Operator Usage in React
📖 Scenario: You are building a simple React component that shows a message based on a user's login status. This is like a welcome sign that changes depending on whether the user is logged in or not.
🎯 Goal: Create a React functional component called StatusMessage that uses a ternary operator to display "Welcome back!" if the user is logged in, or "Please log in." if the user is not logged in.
📋 What You'll Learn
Create a boolean state variable called isLoggedIn with initial value false.
Create a button that toggles the isLoggedIn state between true and false.
Use a ternary operator inside the JSX to show "Welcome back!" when isLoggedIn is true, or "Please log in." when isLoggedIn is false.
Ensure the component updates the message immediately when the button is clicked.
💡 Why This Matters
🌍 Real World
Many websites and apps show different content depending on whether a user is logged in. Using ternary operators in React helps show these changes clearly and simply.
💼 Career
Understanding conditional rendering with ternary operators and managing state is essential for React developers building interactive user interfaces.
Progress0 / 4 steps
1
Set up the React component and state
Create a React functional component called StatusMessage. Inside it, use the useState hook to create a boolean state variable called isLoggedIn with initial value false.
React
Need a hint?

Remember to import useState from React and call it inside your component to create the isLoggedIn state.

2
Add a button to toggle login state
Inside the StatusMessage component, add a button element. When clicked, it should toggle the isLoggedIn state between true and false using the setIsLoggedIn function.
React
Need a hint?

Use an arrow function in the onClick attribute to call setIsLoggedIn with the opposite of the current isLoggedIn value.

3
Use a ternary operator to show the message
Inside the return statement of StatusMessage, add a p element that uses a ternary operator to display "Welcome back!" if isLoggedIn is true, or "Please log in." if isLoggedIn is false.
React
Need a hint?

Use curly braces inside JSX to embed the ternary expression that checks isLoggedIn.

4
Add accessibility and finalize component
Add an aria-live attribute with value polite to the p element to make screen readers announce the message changes politely. Also, add a descriptive aria-label to the button as Toggle login status.
React
Need a hint?

Use aria-live="polite" on the message paragraph and aria-label="Toggle login status" on the button for accessibility.