React Conditional Rendering

React allows you to render components based on specific conditions, providing flexibility in your UI.

Tutorials dojo strip

Using the if Statement

The if statement is a straightforward way to determine which component should be displayed.

First, define two components:

JavaScript

Next, create a component that decides which one to render based on a condition:

JavaScript

Try changing the hasScored attribute to true:

JavaScript

Using the Logical && Operator

The && operator is another method for conditional rendering in React.

Embed JavaScript expressions in JSX using curly braces:

JavaScript

If vehicles.length > 0 evaluates to true, the expression after && will render.

Try emptying the vehicles array:

JavaScript

Using the Ternary Operator

The ternary operator provides a concise way to conditionally render elements.

Syntax

JavaScript

Return the Score component if hasScored is true, otherwise return the Miss component:

JavaScript
Tutorials dojo strip