DEV Community

Taaha hussain Khan
Taaha hussain Khan

Posted on

Conditional Rendering in React

Conditional Rendering in React

In React, you can create distinct components that encapsulate behavior you need. Then, you can render only some of them, depending on the state of your application.

Conditional rendering in React works the same way conditions work in JavaScript. Use JavaScript operators like if or the conditional operator to create elements representing the current state, and let React update the UI to match them.

Here’s an example of conditional rendering in React:

import React from 'react';

function Example(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) {
return ;
}
return ;
}

function UserGreeting(props) {

return

Welcome back!

;

}

function GuestGreeting(props) {

return

Please sign up.

;

}

In this example, the Example component checks the value of isLoggedIn prop and conditionally renders either the UserGreeting or GuestGreeting component.

Top comments (0)