javascript / beginner
Snippet
Conditional UI Rendering Using Ternary Operators in React
In React, conditional rendering controls which UI elements appear based on state conditions. Using the ternary operator (? :) directly inside JSX allows inline branching between two distinct elements depending on boolean state variables.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import React, { useState } from 'react';function UserGreeting() {const [isLoggedIn, setIsLoggedIn] = useState(false);return (<div>{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>}<button onClick={() => setIsLoggedIn(!isLoggedIn)}>Toggle Status</button></div>);}export default UserGreeting;
react
Breakdown
1
const [isLoggedIn, setIsLoggedIn] = useState(false);
Declares a boolean state variable 'isLoggedIn' initialized to false along with its updater function.
2
{isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please sign in.</h1>}
Evaluates 'isLoggedIn' to render a welcome heading if true, or a sign-in prompt if false.
3
<button onClick={() => setIsLoggedIn(!isLoggedIn)}>Toggle Status</button>
Provides a button that toggles the boolean state between true and false upon user interaction.