Better handle conditional rendering in React!

Kunal Jain
tech@iiit-gwalior
Published in
2 min readAug 26, 2023

If you prefer watching videos over reading, a reference video discussing the same is available at the end of the blog. Also, the code being used in the blog is also referenced at the end.

As react developers we come across situations where we are supposed to render components conditionally. We usually tend to use ternary, logical AND, OR and other operators to perform conditional rendering.

However, the problem with directly using these operators within JSX is that the code can become quite messy. This complexity can be amplified when multiple developers are working on the same codebase, making it challenging for one developer to understand another’s code.

<div className="App"> 
{isLoggedIn && <AuthenticatedUser />}
{isLoggedIn && (role === "admin" ? <Admin /> : <User />)}
</div>

This issue of conditionally rendering components can be dealt with a very easy concept of Higher Order Components (HOCs). Higher Order Components are components that can be used as a wrapper over other components and they are responsible for providing extra functionality to their children components.

Let’s proceed to create a Higher Order Component called ConditionalRenderer. This component can be utilized throughout the codebase to achieve conditional rendering of components.

import React from "react";

function ConditionalRenderer({ isVisible, children }) {
return <>{isVisible && children}</>;
}

export default ConditionalRenderer;

This component can be used to rewrite the above mentioned code in a much cleaner and explicit way. By using this component, usage of conditional operators within JSX can be avoided and the code quality can be maintained.

<div className="App">
<ConditionalRenderer isVisible={isLoggedIn}>
<AuthenticatedUser />
</ConditionalRenderer>
<ConditionalRenderer isVisible={isLoggedIn}>
<ConditionalRenderer isVisible={role === "admin"}>
<Admin />
</ConditionalRenderer>
<ConditionalRenderer isVisible={role === "user"}>
<User />
</ConditionalRenderer>
</ConditionalRenderer>
</div>

--

--

tech@iiit-gwalior
tech@iiit-gwalior

Published in tech@iiit-gwalior

Insights into new technologies and concepts for strong hold on existing tech stacks by the student community of IIIT Gwalior

Kunal Jain
Kunal Jain

Written by Kunal Jain

SDE Intern at KoinX | Ex-FamPay | Ex-Trell | IIIT Gwalior'24