One of my first questions when I was learning React was: What if I only want to render a component sometimes? There are many situations where you might want to render a certain component based on the application’s state. For example, you may only want to show a login form if the user isn’t already signed in. So in this tutorial I’ll show you how to render a component conditionally using a simple, concise syntax.
There are a few things you should understand in order to follow along here. You should understand JSX bracket syntax, which is used to embed JavaScript expressions and logic into JSX markup. For example, <h1>Two plus two equals { 2 + 2 }</h1>
.
Second, you should understand Boolean logic and operators. Boolean operators include ===, ==, !==, !, &&,
and ||
.
Finally, you should know how to use the JavaScript conditional operator ( ? :
).
To conditionally render a React component based on state, you’ll use the JSX bracket syntax to embed a Boolean expression into the markup. Then you’ll check the value of the state and return a component based on that state. Here are a few examples:
// I'm not showing the entire components here,
// only the return statements.
// The state variables and components are only illustrative
// Example 1
return (
// This code uses short-circuit evaluation for conciseness
{ isPopupActive && <PopupComponent /> }
)
// Example 2
return (
{ isUserLoggedIn ? <EditProfile /> : <LoginForm /> }
)
// Example 3
// Here, we don't just return a component --
// we return an entire JSX expression inside of parentheses
return (
{ isComponentActive && (
<div>
// JSX markup here
</div>
) }
)