Programming language construct that performs actions according to boolean conditions.
Conditional rendering in React works the same way conditions work in JavaScript. It uses JavaScript operators like if
or the conditional operator to create elements representing the current state, and let React update and render the appropriate components when your data changes.
In simple terms, conditional rendering in React is a way to render different user interface (UI) markup if a condition is true or false. It's a technique where we render different elements or components based on a condition.
There are several ways to use conditional rendering in React. Here are a few common methods:
This is the most straightforward method. You can use if
and else
statements in your component’s render method to decide what to return.
render() { if (this.state.isLoggedIn) { return <UserGreeting />; } else { return <GuestGreeting />; } }
You can use variables to store elements. This can help you conditionally render a part of the component while the rest of the output doesn’t change.
render() { let button; if (this.state.isLoggedIn) { button = <LogoutButton />; } else { button = <LoginButton />; } return ( <div> <Greeting /> {button} </div> ); }
You can embed any expressions in JSX by wrapping them in curly braces. This includes the JavaScript logical &&
operator.
render() { return ( <div> <h1>Hello!</h1> {this.state.isLoggedIn && <LogoutButton /> } </div> ); }
Another method for embedding expressions in JSX is to use the JavaScript conditional operator (condition ? true : false
).
render() { return ( <div> <h1>Hello!</h1> {this.state.isLoggedIn ? ( <LogoutButton /> ) : ( <LoginButton /> )} </div> ); }
In some cases, you might want a component to hide itself even though it was rendered by another component. To do this return null
instead of its render output.
function WarningBanner(props) { if (!props.warn) { return null; } return ( <div className="warning"> Warning! </div> ); }
In the example above, the <WarningBanner />
is rendered depending on the value of the prop called warn
.
By mastering conditional rendering, you can significantly increase the dynamism and interactivity of your React applications.