Multiple Conditional Rendering in React
Handle multiple conditions using a ternary operator.
- Define state and button
- Change state value on button click
- 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:
useState(0)
creates acount
state with an initial value of0
.- The button increases the
count
value on each click. - The JSX uses nested ternary operators to check multiple values of
count
. - Based on the
count
, it conditionally renders different headings.