Write Cleaner Conditional Rendering in React

In this blog, we will discuss how we can write React conditional rendering in a more cleaner efficient way using a custom component.

Tue Jun 07 2022

Write Cleaner Conditional Rendering in React

In this blog, we will discuss how we can write React conditional rendering in a more cleaner efficient way using a custom component.

Conditional rendering is something developers use frequently and in React we use the ‘If’ condition or the ‘Ternary Operator’ to render an element based on a condition. Now take a look at the below snippet,

const value = 10
{
  value === 10 ? <h1>The value is 10</h1> : <h1> The value is not 10 </h1>
}

There is a better way…

In Vue Js, there is something called the v-if directive which conditionally render an element or a template fragment based on the truthy-ness of the expression value. We are going to create something similar.

Step 1:

Create a component called ‘RenderIf’ or whatever name us like in components folder. Below is the code snippet for our RenderIf component.

export const RenderIf = ({ children, when }) => {
  return when ? children : null
}

In this component we pass two props, one is the children which the element that should be rendered and the second prop is the truthiness variable. We can name it as we want, Here I used the word ‘when’. You can name it like showWhen or renderIf or something else if you want to. The child element will be rendered if the condition is true, Else null will be returned.

Step 2:

Now import the newly created RenderIf component and we’re ready to go.

import RenderIf from '../components/RenderIf'
let userLoggedIn = false

<RenderIf when={userLoggedIn}>
  <UserProfile />
</RenderIf>

We can re-use this component, it works really well and our code will look more cleaner.

This article originally appeared on lightrains.com

Leave a comment

To make a comment, please send an e-mail using the button below. Your e-mail address won't be shared and will be deleted from our records after the comment is published. If you don't want your real name to be credited alongside your comment, please specify the name you would like to use. If you would like your name to link to a specific URL, please share that as well. Thank you.

Comment via email
Jishnu Raj
Jishnu Raj

Engineer at Lightrains Technolabs

Tags Recent Blogs