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

Updated on: 18-Mar-2021

372 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements