Ideal Conditions for Conditional Rendering

Ryan Kendig
4 min readMar 11, 2021

--

Here’s a scenario, you’re building a single page React application and you want a user to have the feeling of browsing through multiple pages. Let’s say we have an application for booking entertainment in your area for big moments in one’s life. The home page is a component rendering a collection of artists with some high-level information for each — name, entertainment type, price per event. Now what if I want to click on an artist and see more information? How can we hide the collection of artists and swap them for an individual artist’s show page? Here are the steps to take.

Re-rendering using component state. We want to add functionality to the component state that will toggle a boolean between true and false.

import React, { Component } from "react";import Artist from "./Artist";class Home extends Component {state = {artists: [],selected: {},display: true,};

Using this piece of state, we will write a function that toggles the display between true and false. React will re-render a component every time state changes, so we will write a conditional statement in the render function to show a child component if display: false. This sounds confusing, but what we’re doing is not displaying ALL artists, so we can display a single artist. For this specific example, the we would also need to set state for which individual artist is selected: {} . In order to do that, I need to make a fetch call to my backend Rails app. For the sake of brevity and confusion, I’ll leave the part out. Just trust me that it happened. Here’s the basic function:

toggleDisplay = () = > {
this.setState({ display: !this.state.display})
}

Now that we have a way to toggle our display boolean, we’ll need to add an event handler that calls the function for us. In this example, I called the function using onClick on an individual artist card.

<div id={artist.id} onClick={(e) => this.toggleDisplay(e)}></div>

Now we can add a ternary to the render function in the form of JSX so that we render either the parent component — a collection of artist cards with high-level information, or the child component — a single instance of an artist.

render() {
return (
<div>
<div className="cards">
{this.state.display ? this.generateArtists() : null}
</div>
<div className="selectedArtist">
{!this.state.display ? ( <Artist/> ) : null }
</div>
</div>
)
}

Let’s break down this code. The first bolded portion is stating that if {this.state.display} is true, generate all the artists on the home page, otherwise do nothing. The second bolded portion is saying that if the opposite of {this.state.display} is true, show the child component, <Artist/> . Each ternary will return a value of null if the conditions are not met which is how only one component will be shown at a time.

What we’ve outlined here is known as conditional rendering and it provides the ability to create Single page Applications that are dynamic and interactive using React.

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.

We used this concept to show and hide a component, but there are other applications to this concept such as toggling application functionality and handling authentication and authorization. Ternary operators are not the only way to accomplish conditional rendering. There are obvious alternatives such as using an if…else statement or a switch statement, and less obvious options like Immediately Invoked Function Expressions (IIFE). IIFEs allow you to write and call a function directly within JSX, but wrapped inside an anonymous function.

render() {
<div>
<h1>Super Neat App</h1>
{(function() {
if (loggedIn) {
return <button>Logout</button>
} else {
return <button>Login</>button>
}
})()}
</div>
)
}

Which leads me into one last point. It’s also important to mention that if your conditions are any more complex than toggling a boolean value, it’s best practice to create a separate component for the feature and import it into a parent component. Failure to do could result in performance issues due to constant re-rendering and messier, harder-to-read code for your colleagues.

Conditional rendering is a great technique for creating dynamic and interactive single page web applications. You can create distinct components that provide the functionality you need, and only render some of them depending on the state of your application.

--

--

Ryan Kendig
Ryan Kendig

Written by Ryan Kendig

Player of guitars and games. Learning to code one curly brace at a time.

No responses yet