Thu Jan 07 2021

4 ways to render content conditionally in React

React provides us with the ability to render content and components conditionally and in this post I show you how to achieve this

I can’t say this enough. I love React and all its workings because using it is a pleasure. It is a new frontier for front end development and one I will always remain fascinated by. 

One aspect of React that I find very interesting is conditional rendering and this is an aspect I use quite often when fetching data from backends. I intend on taking you through 4 methods that I use to render React content/components conditionally in this post, but please remember that there are many others that you can use as well. 

So, onwards to the first one.

1. Extracting the render to a function

1import React, { useState } from "react";
2import "./App.css";
3const App = () => {
4 const [status, setStatus] = useState(true);
5 const renderMessage = () => {
6 if (status) {
7 return <h1> I am True </h1>;
8 } else {
9 return <h1> I am False </h1>;
10 }
11 };
12 return (
13 <div>
14 <header className="App-header">
15 {renderMessage()}
16 <button onClick={() => setStatus(!status)}> Change </button>
17 </header>
18 </div>
19 );
20};
21export default App;

What is happening over here is that I change the state using a button click and the  {renderMessage()} function renders different content based on whether the state is True or False.

2. Ternary Operators

The ternary operator is a very concise way of rendering content conditionally. Take a look at the below code where the output is the same as above, with fewer lines of code in it.

1import React, { useState } from "react";
2import "./App.css";
3const App = () => {
4 const [status, setStatus] = useState(true);
5 return (
6 <div>
7 <header className="App-header">
8 <h1>I am now {status ? "True" : "False"}</h1>
9 <button onClick={() => setStatus(!status)}>Change </button>
10 </header>
11 </div>
12 );
13};
14export default App;
15

3. Logical && (Short Circuit Evaluation with &&)

You can use the logical && to render content when one condition is met. So if you look at the code below, you will see that I will display ‘I am true” when the state is made True and “I am False” when the state is made False.

1import React, { useState } from "react";
2import "./App.css";
3const App = () => {
4 const [status, setStatus] = useState(true);
5 return (
6 <div>
7 <header className="App-header">
8 <h1> {status && " I am True"}</h1>
9 <h1>{!status && " I am False"}</h1>
10 <button onClick={() => setStatus(!status)}>Change </button>
11 </header>
12 </div>
13 );
14};
15export default App;
1
2

This however is not the most elegant method  for this particular example as it can clutter the code and make the app rather bloated. 

4. Using Immediately Invoked Function Expressions(IIFEs)

An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined. So the moment you type it out and save it, the function is run.

1import React, { useState } from "react";
2import "./App.css";
3const App = () => {
4 const [status, setStatus] = useState(true);
5 return (
6 <div>
7 <header className="App-header">
8 {(() => {
9 if (status) {
10 return <h1> {status && " I am True"}</h1>;
11 } else {
12 return <h1>{!status && " I am False"}</h1>;
13 }
14 })()}
15 <button onClick={() => setStatus(!status)}>Change </button>
16 </header>
17 </div>
18 );
19};
20export default App;
21

I admit that this is again not the most elegant solution when compared against the ternary operator but it is definitely one you can use in your work. 

Bonus

The methods I showed you so far demonstrated how you can render content or components conditionally. But if you want to display content when only one condition is met? A good example for this is if you want to display a “Profile’ button a user can click to check their profile on the app, only when they are logged in. 

In such a scenario, all you have to is render content when one condition is met using True and Null if False. I have demonstrated this with some code that uses the ternary operator below.

1import React, { useState } from "react";
2import "./App.css";
3const App = () => {
4 const [status, setStatus] = useState(true);
5 return (
6 <div>
7 <header className="App-header">
8 <h1> {status ? " I am now True" : null}</h1>
9 <button onClick={() => setStatus(!status)}>Change </button>
10 </header>
11 </div>
12 );
13};
14export default App;

And there you have it folks! 4 + a Bonus way in which you can can render content conditionally. I hope you found them useful!

Before I sign out, I do want to mention 2 things. 

  1. The code you use to render content conditionally can vary depending on the context. Do however try to follow a certain pattern in order to increase the readability of your code. 

  2. Change only the markup that is concerned with conditional rendering and not all the content. Your component does not need to render more than it has to. 

If you are looking for more quick tip tech articles like this and more, follow me on my social media channels! If not, you can just sign up to my email newsletter below to be notified of any blog post I publish 😊

Comments