DEV Community

Joe Lee
Joe Lee

Posted on

Conditional rendering in React

Here are a few ways to conditionally render your React components:

  1. For multiple components, use a useState hook to decide which component will render and put the setState logic where the user would be making that decision, like clicking a button on a navigation header or choosing an option from a scrolldown.

  2. If you're trying to decide whether or not to render just one component, you can use the in line && syntax. For example, true/false && will render the component if the truthy expression evaluates to true, and will not render if it's false. It's good for toggling displays and making sure the component shows only if it has data.

  3. There is also the inline ? : operator that works as a shorthand for an if-else statement. It first evaluates a truthy expression before the ? and then will run the code after the ? for true, or the code after the : for false. This allows for a quick and easy way to conditionally render two different components that are mutually exclusive.

Top comments (0)