Conditional Rendering in React

The conditional rendering seems to be a standard question on code challenges. I remember when I got it on my test. In fact, I was positively surprised. Well, who doesn’t know how to use conditional rendering. But how many ways do you know?

Conditional rendering in React-speak, it is a way to render different elements or components based on a condition. This concept is applied often in the following scenarios:

  • Rendering external data from an API
  • Showing/hiding elements
  • Toggling application functionality
  • Implementing permission levels
  • Authentication and Authorization

On a simple example base on the value of isLoggedIn in the component state, we want to be able to display a Login button if the user isn’t logged in, and Logoutother way.

import React, { Component } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
isLoggedIn: true
};
}
render() {
return (
<div className="App">
<h1>
This is a Demo showing several ways to implement Conditional Rendering
in React.
</h1>
<button>Login</button>
<button>Logout</button>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

⚫ If / else Statment

An if/else statement allows us to specify that particular action will happen only when the condition is true, as well as do something else if doesn’t.

// index.js
...
render() {
let {isLoggedIn} = this.state;
const renderAuthButton = ()=>{
if(isLoggedIn){
return <button>Logout</button>
} else{
return <button>Login</button>
}
}
return (
<div className="App">
<h1>
This is a Demo showing several ways to implement Conditional Rendering
in React.
</h1>
{renderAuthButton()}
</div>
);
}
...

Multiple return statements

In this method is important to keep the component simple. To do that let’s create another functional component called AuthButton:

// AuthButton.jsimport React from "react";const AuthButton = props => {
let { isLoggedIn } = props;
if (isLoggedIn) {
return <button>Logout</button>;
} else {
return <button>Login</button>;
}
};
export default AuthButton;

AuthButton returns various elements depending on the value of state that is passed down via the isLoggedIn props. Thus we import it in our index.js and pass down the appropriate state as shown below:

// index.js
...
import AuthButton from "./AuthButton";
...
render() {
let { isLoggedIn } = this.state;
return (
<div className="App">
...
<AuthButton isLoggedIn={isLoggedIn} />
</div>
);
}
...

⚫ Using Element Variables

// index.js
...
render() {
let { isLoggedIn } = this.state;
let AuthButton;
if (isLoggedIn) {
AuthButton = <button>Logout</button>;
} else {
AuthButton = <button>Login</button>;
}
return (
<div className="App">
<h1>
This is a Demo showing several ways to implement Conditional Rendering
in React.
</h1>
{AuthButton}
</div>
);
}
...

As you can see we conditionally assign values(components) to AuthButton and then we only have to render it neatly within our JSX.

⚫ Using a Switch Statement

We can conditionally return different markup from components using switch statement where we can specify the markup for various conditions.

// AuthButton.js
import React from "react";
const AuthButton = props => {
let { isLoggedIn } = props;
switch (isLoggedIn) {
case true:
return <button>Logout</button>;
break;
case false:
return <button>Login</button>;
break;
default:
return null;
}
};
export default AuthButton;

This is more reasonable to use when there are more than two possible outcomes.

⚫ Ternary Operators

Sounds scary? No worries, you saw it before, I promise! The conditional (ternary) operator is the only JavaScript operator that takes three operands. This operator is frequently used as a shortcut for the if statement. I didn’t know that this is how we call it too.

// index.js
...
render() {
let { isLoggedIn } = this.state;
return (
<div className="App">
<h1>
This is a Demo showing several ways to implement Conditional Rendering
in React.
</h1>
{isLoggedIn ? <button>Logout</button> : <button>Login</button>}
</div>
);
}
...

⚫ Logical &&

Short circuit evaluation (that is the name of the technic) is a technique used to ensure that there are no side effects during the evaluation of operands in an expression.

// index.js
...
render() {
let { isLoggedIn } = this.state;
return (
<div className="App">
<h1>
This is a Demo showing several ways to implement Conditional Rendering
in React.
</h1>
{isLoggedIn && <button>Logout</button>}
</div>
);
}
...

The logical &&is letting us specify that an action should be taken only when the condition is true, otherwise, it would be ignored entirely. It is useful for situations when we only need to take any action in one condition.

⚫ Using IIFEs

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. Read more here.

//index.js
...
render() {
let { isLoggedIn } = this.state;
return (
<div className="App">
<h1>
This is a Demo showing several ways to implement Conditional Rendering
in React.
</h1>
{(function() {
if (isLoggedIn) {
return <button>Logout</button>;
} else {
return <button>Login</button>;
}
})()}
</div>
);
}
...

In this technique, we are using an anonymous function that is immediately invoked on an evaluation of that portion of the code.

SOFTWARE ENGINEER — WEB DEVELOPER WITH HEART FOR FRONT-END, MINIMALISM AND RASMENTALISM.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store