In React apps, you’ll often need to render different UI components conditionally based on certain state. For example, showing a login form if a user is not authenticated, or displaying different content based on configurable settings.
Here are useful patterns for conditional rendering in React:
If/Else Statements
The standard JS if/else statement works in JSX too:
function App() {
const loggedIn = false;
if (loggedIn) {
return <WelcomeMessage />;
} else {
return <LoginForm />;
}
}
This will render either the WelcomeMessage
or LoginForm
component based on the value of loggedIn
.
Ternary Operator
function App() {
const isLoading = true;
return (
<div>
{isLoading ? <Loader /> : <Content />}
</div>
)
}
If isLoading
is truthy, it will render the Loader, else render Content.
Short Circuit Evaluation
You can take advantage of JS short circuit evaluation:
function App() {
const showAlert = false;
return (
<div>
{showAlert && <Alert />}
</div>
)
}
If showAlert
is falsy, React won’t even evaluate the <Alert />
expression.
Element Variables
You can store elements in variables for conditional rendering:
function App() {
let message;
if (user) {
message = <WelcomeMessage />;
} else {
message = <SignUpMessage />;
}
return <div>{message}</div>;
}
Preventing Component Rendering
For more control, you can return null
to prevent rendering:
function App(props) {
if (!props.authorized) {
return null;
}
return <AdminPanel />;
}
By returning null, App
won’t render anything if props.authorized
is falsy.
Showing/Hiding Elements
Another option is conditionally applying the hidden
attribute:
return (
<div>
<Alert hidden={!error} />
</div>
)
The Alert
will be hidden if error
is falsy.
Conclusion
There are a few different ways to conditionally render in React:
- If/else statements
- Ternary expressions
- Short circuit evaluation
- Returning null or using hidden attributes
Choose the right method based on your use case. Conditional rendering is essential for building reusable React components that adapt to different states.