Open In App

How to conditionally render components in ReactJS ?

Last Updated : 30 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

React is a declarative, efficient, and flexible JavaScript library for building user interfaces. It’s ‘V’ in MVC. ReactJS is an open-source, component-based front-end library responsible only for the view layer of the application. It is maintained by Facebook.

Prerequisites:

Conditional Rendering:

To create multiple components and render them based on some conditions. This is also a kind of encapsulation supported by React. When UI is designed using React, we come across a situation when components are to be rendered on the screen based on some condition. For eg, In a University Information System, when a teacher login, different components are rendered whereas when a student login, different components are rendered. This is called the Conditional Rendering of React Components.

Syntax:

{statement} ? true : false 

How to do Conditional Rendering?

It is done using stateVariable. The value of the stateVariable determines whether to render the component or not. Its value can be changed by the occurrence of any event like onClick.

Steps to Create the React Application And Installing Module:

Step 1: Create a react application using the following command.

npx create-react-app foldername

Step 2: Once it is done, change your directory to the newly created application using the following command.

cd foldername

Project Structure:

The updated dependencies in package.json file will look like:

"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4",
}

Example 1: We will use a stateVariable; isLoggedIn, and it is set to false initially. Its value is toggled using a button. If isLoggedIn is false then the user is logged out and if it is true then the user is logged in. When a user is logged in, then using the condition operator, the component is rendered on the screen. 

Javascript




import React from 'react'
import { useState } from 'react';
import Card from '@mui/material/Card';
import CardContent from '@mui/material/CardContent';
import CardMedia from '@mui/material/CardMedia';
import Typography from '@mui/material/Typography';
import { CardActionArea } from '@mui/material';
import Divider from '@mui/material/Divider';
import Stack from '@mui/material/Stack';
function DisplayLoggedOut() {
    return (
        <div style={{ background: 'green' }}>
            <h1 style={{ color: 'white' }}> Please Login</h1>
        </div>
    )
}
function DisplayLoggedIn() {
    return (
        <div >
            <div style={{ background: 'green' }}>
                <h1 style={{ color: 'white' }}> You are Logged In</h1>
            </div>
            <h3>Courses available on GeeksforGeeks</h3>
            <div style={{ display: 'inline' }}>
                <Card sx={{ maxWidth: 345 }} >
                    <CardActionArea>
                        <CardMedia
                            component="img"
                            height="140"
                            image=
                            alt="green iguana"
                        />
                        <CardContent>
                            <Typography gutterBottom variant="h5"
                                component="div">
                                Java
                            </Typography>
                            <Typography variant="body2"
                                color="text.secondary">
                                The Java codes are first compiled into byte
                                code (machine-independent code). Then the byte
                                code runs on Java Virtual Machine (JVM)
                                regardless of the underlying architecture.
                            </Typography>
                        </CardContent>
                    </CardActionArea>
                </Card>
            </div>
        </div>
    )
}
function Rendering() {
    const [isLoggedIn, setIsLoggedIn] = useState(false);
    const handleLoginButton = () => {
        if (isLoggedIn) {
            setIsLoggedIn(false);
        }
        else {
            setIsLoggedIn(true);
        }
    }
    return (
        <div>
            <h1 style={{ color: 'green' }}>GeeksforGeeks</h1>
            <h3>Conditionally Rendering Components in React</h3>
            {isLoggedIn == false ? <DisplayLoggedOut /> : <DisplayLoggedIn />}
            <button onClick={handleLoginButton} className="btn btn-primary">
                {isLoggedIn == false ? 'Log In' : 'Log Out'}
            </button>
        </div>
    )
}
function App() {
    return (
        <div className="App">
            <Rendering />
        </div>
    );
}
export default App;


Step to Run the application: Run your app by executing the below command in the src 

npm start 

Output:

Example 2: We have displayed a Bootstrap table after a user is logged in, using: 

import Table from 'react-bootstrap/Table'

Javascript




import React from 'react'
import { useState } from 'react';
import Table from 'react-bootstrap/Table'
function DisplayLoggedOut() {
    return (
        <div style={{ background: 'green' }}>
            <h1 style={{ color: 'white' }}> Please Login</h1>
        </div>
    )
}
function DisplayLoggedIn() {
    return (
        <div >
            <div style={{ background: 'green' }}>
                <h1 style={{ color: 'white' }}> You are Logged In</h1>
            </div>
            <h3>List of Students</h3>
            <div style={{ display: 'inline' }}>
                <Table hover >
                    <thead >
                        <tr>
                            <th scope="col">#</th>
                            <th scope="col">First</th>
                            <th scope="col">Last</th>
                            <th scope="col">Address</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <th scope="row">1</th>
                            <td>Muskan</td>
                            <td>Roomie</td>
                            <td>Lucknow</td>
                        </tr>
                        <tr>
                            <th scope="row">2</th>
                            <td>Pratiksha</td>
                            <td>Singh</td>
                            <td>Ajamgarh</td>
                        </tr>
                        <tr>
                            <th scope="row">3</th>
                            <td>Nishi</td>
                            <td>Mehrotra</td>
                            <td>Prayagraj</td>
                        </tr>
                    </tbody>
                </Table>
            </div>
        </div>
    )
}
function Rendering() {
    const [isLoggedIn, setIsLoggedIn] = useState(false);
    const handleLoginButton = () => {
        if (isLoggedIn) {
            setIsLoggedIn(false);
        }
        else {
            setIsLoggedIn(true);
        }
    }
    return (
        <div>
            <h1 style={{ color: 'green' }}>GeeksforGeeks</h1>
            <h3>Conditionally Rendering Components in React</h3>
            {isLoggedIn == false ? <DisplayLoggedOut /> : <DisplayLoggedIn />}
            <button onClick={handleLoginButton} className="btn btn-primary">
                {isLoggedIn == false ? 'Log In' : 'Log Out'}
            </button>
        </div>
    )
}
function App() {
    return (
        <div className="App">
            <Rendering />
        </div>
    );
}
export default App;


Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads