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:
The standard JS if/else statement works in JSX too:
This will render either the
LoginForm component based on the value of
isLoading is truthy, it will render the Loader, else render Content.
Short Circuit Evaluation
You can take advantage of JS short circuit evaluation:
showAlert is falsy, React won’t even evaluate the
<Alert /> expression.
You can store elements in variables for conditional rendering:
Preventing Component Rendering
For more control, you can return
null to prevent rendering:
By returning null,
App won’t render anything if
props.authorized is falsy.
Another option is conditionally applying the
Alert will be hidden if
error is falsy.
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.