Skip to main content

Conditional Rendering for functional components

Conditional rendering in functional components is similar to how it is done in class-based components. You can use JavaScript's built-in control flow statements, such as if-else or ternary operators, to determine which elements to render.

For example, you can use a ternary operator to conditionally render a message depending on a certain condition:

function ExampleComponent(props) {
const isLoading = props.isLoading;
return (
<div>
{isLoading ? <p>Loading...</p> : <p>Loaded!</p>}
</div>
);
}

In this example, if the isLoading prop is true, the component will render the message "Loading...". Otherwise, it will render the message "Loaded!".

Another way to do conditional rendering is by using the if statement inside the return statement:

function ExampleComponent(props) {
const isLoading = props.isLoading;
return (
<div>
{if (isLoading) {
return <p>Loading...</p>;
} else {
return <p>Loaded!</p>;
}}
</div>
);
}

You can also use the && operator to render a component only if a certain condition is true:

function ExampleComponent(props) {
const isLoading = props.isLoading;
return (
<div>
{isLoading && <p>Loading...</p>}
</div>
);
}

In this example, the <p>Loading...</p> element will only be rendered if the isLoading prop is true.

It's important to note that in React, it's best to avoid using index as a key when looping through an array of items to render. Instead, use a unique identifier if possible.