Conditional Rendering
In React, conditional rendering is a technique used to show different components or UI elements based on a condition. It allows you to control what gets rendered based on the state or props of a component.
If-Else Statements
One way to implement conditional rendering is by using if-else statements. You can define conditions in your component's render method and return different components based on those conditions.
1const Greeting = ({ isLoggedIn }) => {
2 if (isLoggedIn) {
3 return <h1>Welcome back!</h1>;
4 } else {
5 return <h1>Please log in.</h1>;
6 }
7};
In the example above, the Greeting
component renders different greetings depending on whether the isLoggedIn
prop is true or false.
Ternary Operator
Another way to perform conditional rendering is by using the ternary operator (? :
). It allows you to write a more concise and inline if-else statement.
1const Greeting = ({ isLoggedIn }) => (
2 isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>
3);
The above code snippet achieves the same result as the previous example, but in a more concise way using the ternary operator.
Logical && Operator
You can also use the logical AND (&&
) operator to conditionally render components. This approach is useful when you want to conditionally render a component only if a certain condition is met.
1const Greeting = ({ name }) => (
2 name && <h1>Hello, {name}!</h1>
3);
In the example above, the Greeting
component only renders the greeting if the name
prop is truthy.
Conditional rendering is a powerful feature in React that allows you to create dynamic and responsive UIs. By choosing the appropriate method (if-else, ternary operator, or logical && operator) based on your specific use case, you can control what gets rendered in your React components.
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);
}
}