Here are a few ways to conditionally render your React components:
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.
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.
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)