Conditional rendering is the act of showing/hiding your elements/components based on the state of your application. Just like in any framework/language this can be done in React with basic if statements thanks to React just being plain Javascript.
The following example will test the name variable and if truthy will return Hello ${name} and if falsy will return Hello
function App() {
const name = "Bernie";
return <div>{name ? `Hello ${name}!` : "Hello!"}</div>;
}
The above example uses a simple ternary operator to select between simple text choices. This is useful in situations where you might be defining the text based on the users’ logged in/out status.
What if you want to conditionally render an entire component?
This is effectively the same as our above component except in place of plain-text you can just put whatever components you want to render. For example:
function App() {
const name = undefined;
return <div>{name ? <MyAwesomeComponent /> : <MyNotSoAwesomeComponent />}</div>;
}
What if my conditional logic is more complex than a simple known boolean?
For more complex conditions you probably won’t want to include all the logic to select what components to show in the return statement of your function/class. In these situations you can just set the value of a variable to be the element/component that you want to render. For example:
function App() {
let component;
const awesome = true;
if (awesome !== undefined) {
component = <MyAwesomeComponent />;
}
else {
component = <MyNotSoAwesomeComponent/>;
}
return <div>
<h1>Behold my conditional component</h1>
{component}
</div>;
}
Logical conjunction with boolean operands
A.K.A. short circuiting a boolean expression. This involves using the logical && operator to test a boolean expression and output JSX based on the result.
It’s far less complicated when you look at an example like this:
function App() {
const awesome = true;
return <div>
<h1>Behold my conditional component</h1>
{awesome && <MyAwesomeComponent />}
</div>;
}
All we are doing is using the fact that the && operator will stop as soon as it hits a falsy value or if all values are truth then the last operand will be returned. So in our example above, <MyAwesomeComponent /> will be returned if awesome is true.
No variation of conditional rendering should be considered most correct when developing your applications, the important thing is being able to keep your code clean, so use whatever style suits best.