Conditional rendering in React allows you to render different components or elements based on certain conditions. There are multiple ways to achieve conditional rendering in React. Here are a few common methods along with examples:
You can use a ternary operator to conditionally render different JSX elements based on a condition.
import React from 'react'; function ConditionalRendering({ isLoggedIn }) { return ( <div> {isLoggedIn ? ( <p>Welcome, User!</p> ) : ( <div> <p>Please log in to continue.</p> <button>Login</button> </div> )} </div> ); } export default ConditionalRendering;
&&
OperatorYou can use the logical AND (&&
) operator to conditionally render JSX.
import React from 'react'; function ConditionalRendering({ isLoggedIn }) { return ( <div> {isLoggedIn && <p>Welcome, User!</p>} {!isLoggedIn && ( <div> <p>Please log in to continue.</p> <button>Login</button> </div> )} </div> ); } export default ConditionalRendering;
if
StatementsYou can also use regular if
statements for conditional rendering, but they must be inside a function component.
import React from 'react'; function ConditionalRendering({ isLoggedIn }) { if (isLoggedIn) { return <p>Welcome, User!</p>; } else { return ( <div> <p>Please log in to continue.</p> <button>Login</button> </div> ); } } export default ConditionalRendering;
You can use switch
statements for more complex conditional rendering.
import React from 'react'; function ConditionalRendering({ userType }) { switch (userType) { case 'admin': return <p>Welcome, Admin!</p>; case 'user': return <p>Welcome, User!</p>; default: return <p>Please log in to continue.</p>; } } export default ConditionalRendering;
You can also use component state to manage the condition and render accordingly.
import React, { useState } from 'react'; function ConditionalRendering() { const [isLoggedIn, setIsLoggedIn] = useState(false); const toggleLogin = () => { setIsLoggedIn(!isLoggedIn); }; return ( <div> {isLoggedIn ? ( <p>Welcome, User!</p> ) : ( <div> <p>Please log in to continue.</p> <button onClick={toggleLogin}>Login</button> </div> )} </div> ); } export default ConditionalRendering;