Intro to React > Conditional Rendering
Conditional Rendering
As we looked at in the primitives lesson, when booleans are placed in JSX, nothing is rendered to the screen. This is useful when you only want to show an element under certain circumstances.
A boolean expression, like showUsers && <div> ...
, is just normal JavaScript. When showUsers
is false, the whole expression evaluates to false
, and so false
is the end result. However, when showUsers
is true, the right hand of the expression is also evaluated, and if it results in a truthy expression, it will be returned and thus rendered in the app.
Note that you don't want too much logic inside your JSX. Often, it's cleaner to abstract some of your logic above the JSX.
export default function App() { const renderMe = true; return ( <div> <h1> Captain's Tasks </h1> {renderMe ? "This renders!" : "Does not render!"} {renderMe && <div> This also renders </div>} </div> ); }