Multiple Conditional Rendering in React

Handle multiple conditions using a ternary operator.


  1. Define state and button
  2. Change state value on button click
  3. Apply Condition with state



Counter with Multiple Conditions

import { useState } from "react";

function App() {
const [count, setCount] = useState(0);

return (
<div>
<h1>{count}</h1>
<button onClick={() => setCount(count + 1)}>Counter</button>

{
count === 0 ? <h1>Condition 0</h1>
: count === 1 ? <h1>Condition 1</h1>
: count === 2 ? <h1>Condition 2</h1>
: count === 3 ? <h1>Condition 3</h1>
: count === 4 ? <h1>Condition 4</h1>
: <h1>Other Condition</h1>
}
</div>
);
}

export default App;


How It Works:

  1. useState(0) creates a count state with an initial value of 0.
  2. The button increases the count value on each click.
  3. The JSX uses nested ternary operators to check multiple values of count.
  4. Based on the count, it conditionally renders different headings.