Conditional Rendering in React

When you are building react applications you may often need to show or hide some HTML based on a certain condition luckily conditional rendering in react works the same way conditions work in JavaScript we have four different approaches and we will take a detailed look at each one of them.

  1. If / Else

  2. Element Variables

  3. Ternary Conditional Operator

  4. Short Circuit Operator

First, let's see the if / else approach

Create a new file UserGreeting.js inside a component folder. I am creating a class component for UserGreeting.js and the code looks like this :

UserGreeting.js

import React, {Component} from 'react'

class UserGreeting extends Component {
    render () {
        return (
            <div>
                Welcome Shaad
            </div>
        )
    }
}

export default UserGreeting

Import the UserGreeting class inside the App.js

App.js

import React from 'react';
import './App.css';
import UserGreeting from './components/UserGreeting';

function App() {
  return (
    <div className="body">
      <UserGreeting />
    </div>
  )
}

export default App

Now if we save the file and take a look at the browser then we will see the "Welcome Shaad" message

Now, I am going to make some changes to the UserGreeting.js. I am adding a constructor, within the constructor and adding a super method and defining the state. I am going to create a one state property called a logged property and initialize it to false.

constructor(props) {
        super(props)

        this.state = {
            logged: false
        }
}

1. If / Else Approach

Now I want that if I am logged in then the message Welcome Shaad should be displayed if I am not logged in then the message Welcome Guest should be displayed. Let's see how to achieve this. The first approach is to use the If / Else condition.

Now in the render method, I will add the if / else condition.

if (this.state.logged) {
            return (
                <div>
                    Welcome Shaad
                </div>
            )
        }

        else {
            return (
                <div>
                    Welcome Guest
                </div>
            )
}

Now if we save the file and go to the browser we will get the message Welcome Guest because the value of the logged is set to false.

If I change it to true then again I will get a Welcome Shaad message.

2. Element Variable Approach

The next better approach is the Element Variable approach. In this approach, we will use JavaScript variables to store the elements. This will also help you conditionally render the entire component or a part of the component as well.

Now I am going to comment out the if/else code and then declare a variable inside the render method. Now we will store the appropriate element in this variable based on the condition. In the end, we return the message.

let message

if (this.state.logged)
{
    message = <div>Welcome Shaad</div>
}

else {
    message = <div>Welcome Guest</div>
}

return <div>{message}</div>

3. Ternary Conditional Operator

This approach is much simpler than the Element Variable method. This approach uses a ternary condition operator. The benefit of this approach is that it can be used in the JSX.

return (
            this.state.logged ?
                <div>Welcome Shaad</div> :
                <div>Welome Guest</div>
 )

So the first operator this.state.logged is checked whether it is true or false. If it is true then the second operator that is the div tag that contains Welcome Shaad is returned else if it is false then the third operator is returned that is the div tag that contains Welcome Guest.

4. Short Circuit Operator Approach

The last approach is the short circuit operator approach. This approach is just the specific case of the ternary operator approach. When we want to render something or nothing, we make use of the Short Circuit operator.

Let's suppose if the user logged in then we want to display Welcome Shaad, if the user is not logged in then we want to render nothing on to the screen. We will add the following line in the render method.

return (
            this.state.logged && <div>Welcome Shaad</div>
)

Here, if this.state.logged is true then it will display Welcome Shaad but if the value of logged is false then it won't display anything as the false value of this.state.logged won't affect the final value of the whole expression.

So these are the four approaches of conditional rendering in React.

Right now I am learning React so I am documenting whatever I am learning. I hope you found this blog helpful if yes then do follow for more such blogs in future.

Thank you for reading :)

0
Subscribe to my newsletter

Read articles from MOHAMMAD SHAAD SHAIKH directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

MOHAMMAD SHAAD SHAIKH
MOHAMMAD SHAAD SHAIKH

Hi there! I'm a web developer with a passion for creating intuitive, user-friendly websites. With a year of experience under my belt, I have a strong understanding of the latest technologies and best practices in the industry. Whether I'm working on a small personal project or a large-scale enterprise solution, I always strive to deliver high-quality code and a great user experience. I'm excited to be part of the Hashnode community and look forward to connecting with other like-minded developers. Let's build something amazing together!