Conditional component rendering lets your app show or hide parts based on conditions. It helps make your app interactive and dynamic.
Conditional component rendering in React
function MyComponent({ isLoggedIn }) { return ( <div> {isLoggedIn ? <p>Welcome back!</p> : <button>Login</button>} </div> ); }
Use JavaScript expressions inside curly braces {} to decide what to render.
The ternary operator condition ? truePart : falsePart is common for conditional rendering.
function Greeting({ isMorning }) { return <div>{isMorning ? 'Good morning!' : 'Good evening!'}</div>; }
show is true.function ShowMessage({ show }) { return <div>{show && <p>This message is visible.</p>}</div>; }
switch to render different components based on status.function Status({ status }) { switch (status) { case 'loading': return <p>Loading...</p>; case 'error': return <p>Error occurred.</p>; default: return <p>Ready.</p>; } }
This component shows a login button if the user is not logged in. When clicked, it changes state to logged in and shows a welcome message with a logout button. Clicking logout switches back.
Buttons have aria-label for accessibility.
import React, { useState } from 'react'; function LoginControl() { const [isLoggedIn, setIsLoggedIn] = useState(false); function handleLogin() { setIsLoggedIn(true); } function handleLogout() { setIsLoggedIn(false); } return ( <div> {isLoggedIn ? ( <> <p>Welcome back!</p> <button onClick={handleLogout} aria-label="Logout button">Logout</button> </> ) : ( <button onClick={handleLogin} aria-label="Login button">Login</button> )} </div> ); } export default LoginControl;
Always use semantic HTML elements like <button> for clickable items.
Use aria-label to help screen readers describe buttons clearly.
Keep conditions simple to avoid confusing code.
Conditional rendering lets you show or hide parts of your UI based on data or state.
Use JavaScript expressions inside JSX with {} to decide what to render.
Common patterns include ternary operators, logical AND, and switch statements.