Conditional Rendering in React

Soner Mezgitci
5 min readApr 2, 2021

In React, we can create multiple components which encapsulate behavior that we need. After that, we can render them depending on some conditions or the state of our application. In other words, based on one or several conditions, a component decides which elements it will return. In React, conditional rendering works the same way as the conditions work in JavaScript. We use JavaScript operators to create elements representing the current state, and then React Component update the UI to match them.

We will have 4 different approaches and we will take a detailed look at each of them

Conditional Rendering

  1. if/else

2. Element variables

3. Ternary conditional operator

4. Short circuit operator

From the given scenario, we can understand how conditional rendering works. Consider an example of handling a state isLoggedIn . If a user logged in, render the Welcome Soner to display in the browser . If a user not logged in, render the Welcome Guest to display in the browser. In React, this situation is called as conditional rendering.

There is more than one way to do conditional rendering in React. They are given below.

import React, { Component } from 'react'class UserGreeting extends Component {
constructor(props) {
super(props)

this.state = {
isLoggedIn: false
}
}
render() {
if (this.state.isLoggedIn) {
return ( <div> Welcome Soner </div>) } else { return ( <div> Welcome Guest </div> ) } }}export default UserGreeting

As you see i created one state property called IsLoggedIn and initialized it to false. We also added if else condition on our render method. If IsLoggedIn we should return Welcome Soner otherwise we should get return Welcome Guest.

If else Statements does not work inside the JSX. Because JSX just Syntactic Sugar for function calls and object construction adding if else statements within the JSX is not valid that is the reason we have if else statements outside the JSX and entire return statement containing JSX inside the if or else block.

Element variable

You use Java Script variables to store elements. This will also help you conditionally render entire component or a part of the component as well. Element variables are simply variables that hold JSX elements. By using variables to store components or some values we can render a part of the component while the rest of the output doesn’t change.

Let’s take a look at the following code so that you can understand what I mean.

import React, { Component } from 'react'class UserGreeting extends Component {     constructor(props) { 
super(props)

this.state = {
isLoggedIn: false
}
}
render() {
let message
if (this.state.isLoggedIn) {
message = <div> Welcome Soner</div>
} else {
message = <div> Welcome Guest </div>
}
return <div> {message}</div>
} }export default UserGreeting

As you see we declared a variable (message) inside in render method. We store appropriate element in this variable based on the condition. So basically we are saying if isLoggedIn is true logged in message is going to be Welcome Soner otherwise message is equal to Welcome Guest. We are returning message variable.

Ternary Conditional Operator

It’s true that we can use JavaScript in JSX, but it becomes difficult when using statements like if, else, and switch case within JSX. There is no real way to inline it .Ternary operator can use inside the JSX.

import React, { Component } from 'react'class UserGreeting extends Component { 
constructor(props) {
super(props)
this.state =
isLoggedIn: false
} } render() { return (
this.state.isLoggedIn ?
<div> Welcome Soner</div> :
<div> Welcome Guest</div>
)
}}

As you see we can set our ternary operator in return method. We are basically saying IsLoggedIn in evaluated to either true or false. If its true second operator is return Welcome Soner. If the first operator is false it will return 3rd operator which is Welcome Guest.
Actually Ternary Operator is most popular conditional statements If you need to render conditionally in your application. Its very short line of code. It’s simple and readable you can also use it inside the return.

Short Circuit Operator

We use this operator if we have return something or not. It’s very similar to Ternary operator but the only difference we wither return something or nothing. Regarding our previous example, We return Welcome Soner or Welcome Guest. But it’s different in this operator.

import React, { Component } from 'react'class UserGreeting extends Component {     constructor(props) {       super(props)
this.state = {
isLoggedIn: false
}} render() {
return this.state.isLoggedIn && <div> Welcome Soner</div>
}
}

When the user isLoggedIn we return the Welcome Soner or nothing. Expression first evaluates left hand side of the operator. If isLoggedIn is true also evaluated right hand side which in our case rendering with JSX in the browser. If left hand side evaluates to false the right hand side will never be evaluated as it does not affect the final value of the whole expression.

Higher Order Components

Higher order components or HOCs are often considered a difficult pattern to grasp in ReactJS. HOCs can be used for multiple use cases, however in this article, we’ll be picking up HOC for conditional rendering.

HOCs are a perfect match for conditional rendering in React and can have several use cases. One of them can be to alter the look of a component. To make it more specific, it can be used to conditionally render the component itself.

Preventing Component from Rendering

In rare 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.

In the example below, the <WarningBanner /> is rendered depending on the value of the prop called warn. If the value of the prop is false, then the component does not render:

function WarningBanner(props) {
if (!props.warn) { return null; }
return (
<div className="warning">
Warning!
</div>
);
}

class Page extends React.Component {
constructor(props) {
super(props);
this.state = {showWarning: true};
this.handleToggleClick = this.handleToggleClick.bind(this);
}

handleToggleClick() {
this.setState(state => ({
showWarning: !state.showWarning
}));
}

render() {
return (
<div>
<WarningBanner warn={this.state.showWarning} /> <button onClick={this.handleToggleClick}>
{this.state.showWarning ? 'Hide' : 'Show'}
</button>
</div>
);
}
}

ReactDOM.render(
<Page />,
document.getElementById('root')
);

Conclusion

In summary, we saw 4 different ways to conditional rendering in React. Each approach has its own advantages and some are short and readable. My suggestion would be using If Else conditional statement or Short Circuit Operator. They tend to more clean and readable.

--

--

Soner Mezgitci

Software Engineer | Ruby on Rails | JavaScript | HTML5 | CSS | PostgreSQL | React | Redux