Conditional Rendering in React
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:
This will render either the WelcomeMessage
or LoginForm
component based on the value of loggedIn
.
Ternary Operator
If isLoading
is truthy, it will render the Loader, else render Content.
Short Circuit Evaluation
You can take advantage of JS short circuit evaluation:
If showAlert
is falsy, React won’t even evaluate the <Alert />
expression.
Element Variables
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.
Showing/Hiding Elements
Another option is conditionally applying the hidden
attribute:
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.