Skip to content
Related Articles
Open in App
Not now

Related Articles

How to conditionally render components in ReactJS ?

Improve Article
Save Article
  • Last Updated : 28 Mar, 2022
Improve Article
Save Article

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.

When UI is designed using React, we come across a situation when components are to be rendered on the screen based upon some condition. For eg, In a University Information System, when a teacher logins, then different components are rendered whereas when student logins, different components are rendered.

This is called Conditional Rendering of React Components.

Conditional Rendering: To create multiple components and render them based on some conditions. This is also a kind of encapsulation supported by React.

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.

Creating React Application:

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 project structure should look like this:

Example 1: In this example, 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. 

Condition Operator:

{statement} ? true : false 

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:


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!