Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Conditional Rendering in ReactJS
In this article, we are going to see how to conditionally render a component based on some conditions in a React application
In ReactJS, we can render only the desired components based on certain given conditions by using the if-else statements or by using the logical && operator of JavaScript. When the provided condition is satisfied, then React will match the UI and update it accordingly.
Using if-else conditions
Example
In this example, we will build a React application that has an App component as a parent component which will conditionally re-render the Form component and update the UI accordingly.
App.jsx
import React, { useState } from 'react';
const App = () => {
const [isLogin, setIsLogin] = useState(true);
return (
<div>
<div>Username: Tutorialspoint</div>
<div onClick={() => setIsLogin((prev) => !prev)}>
{isLogin ? <Form login /> : <Form logout />}
</div>
</div>
);
};
const Form = ({ login, logout }) => {
return (
<div>
{login ? (
<>
<input placeholder="Email" />
<input placeholder="Password" />
<button>Login</button>
</>
) : null}
{logout ? (
<button>Logout</button>
) : null}
</div>
);
};
export default App;
Output

Using logical &&
Example
App.jsx
import React, { useState } from 'react';
const App = () => {
const [isLogin, setIsLogin] = useState(true);
return (
<div>
<div>Username: Tutorialspoint</div>
<div onClick={() => setIsLogin((prev) => !prev)}>
{isLogin ? <Form login /> : <Form logout />}
</div>
</div>
);
};
const Form = ({ login, logout }) => {
return (
<div>
{login && (
<>
<input placeholder="Email" />
<input placeholder="Password" />
<button>Login</button>
</>
)}
{logout && (
<button>Logout</button>
)}
</div>
);
};
export default App;
Output

Advertisements