Nearby lessons

10 of 44

⚛️ ReactJS – Conditional Rendering

📌 What is Conditional Rendering?

When you are building React applications, you may often need to show or hide HTML based on a certain condition. Conditional rendering in React works the same way as conditions in JavaScript. In React, you can conditionally render components or elements using if else, &&, or the ternary operator.

📌 if else Statement

You can use the traditional if else statement to render components conditionally in React.

React Playground
import React from 'react';
import Component1 from './Component1.jsx';
import Component2 from './Component2.jsx';

const App = () => {
  let name = "Shiva";
  if(name === "Shiva"){
    return <Component1/>
  } else {
    return <Component2/>
  }
}

export default App;

📌 if else with Variable Assignment

Instead of returning components directly inside if else, you can assign the result to a variable and then return it inside JSX.

React Playground
import React from 'react';
import Component1 from './Component1.jsx';
import Component2 from './Component2.jsx';

const App = () => {
  let name = "Shiva";
  let data;

  if(name === "Shiva"){
    data = <Component1/>
  } else {
    data = <Component2/>
  }

  return(
    <>
      {data}
    </>
  )
}

export default App;

📌 Logical && Operator

You can use the && operator for conditional rendering. If the condition is true, the right-hand side expression will render.

React Playground
import React from 'react';
import Component1 from './Component1.jsx';

const App = () => {
  let name = "Shiva";
  return(
    <>
      {name === "Shiva" && <Component1/>}
    </>
  )
}

export default App;

📌 Ternary Operator ? :

The ternary operator is the most common way to handle conditional rendering. Syntax: (condition ? expr1 : expr2).

React Playground
import React from 'react';

const App = () => {
  let age = 22;
  return(
    <>
      { age >= 18 ? <h1>You can vote</h1> : <h1>You can't vote</h1> }
    </>
  )
}

export default App;

📌 Ternary Operator with Components

You can also use the ternary operator to render components conditionally.

React Playground
import React from 'react';
import Component1 from './Component1.jsx';
import Component2 from './Component2.jsx';

const App = () => {
  let name = "Rajesh";
  return(
    <>
      { name === "Rajesh" ? <Component1/> : <Component2/> }
    </>
  )
}

export default App;

🧠 Test Your Knowledge

4 Questions

Progress: 0 / 4
Keep Going!React - Rendering Lists