Conditional Rendering
In React, conditional rendering allows you to render components conditionally based on certain conditions. This is particularly useful when you want to show different content or UI elements depending on the current state or props of your component.
Conditional rendering in React can be achieved in multiple ways, including using conditional statements such as if
and else
, and using the ternary operator
and logical operators
.
Let's take a look at an example where we render different messages based on a count value:
1import React, { useState } from 'react';
2
3function ConditionalRenderingExample() {
4 const [count, setCount] = useState(0);
5
6 return (
7 <div>
8 <button onClick={() => setCount(count + 1)}>Increment Count</button>
9 <hr>
10 {count % 2 === 0 ? (
11 <p>Count is even: {count}</p>
12 ) : (
13 <p>Count is odd: {count}</p>
14 )}
15 </div>
16 );
17}
18
19export default ConditionalRenderingExample;
In this example, a button is rendered with the text 'Increment Count'. When the button is clicked, the setCount
function is called, which updates the count state.
The ternary operator
is used inside the JSX to conditionally render different messages based on whether the count is even or odd.
You can also use logical operators like &&
and ||
to conditionally render elements based on multiple conditions.
Conditional rendering is a powerful feature in React that allows you to create dynamic and flexible user interfaces. By rendering components conditionally, you can tailor the UI to specific scenarios and provide a personalized user experience.
xxxxxxxxxx
// replace with ts logic relevant to content
// make sure to log something
for (let i = 1; i <= 100; i++) {
if (i % 3 === 0 && i % 5 === 0) {
console.log("FizzBuzz");
} else if (i % 3 === 0) {
console.log("Fizz");
} else if (i % 5 === 0) {
console.log("Buzz");
} else {
console.log(i);
}
}