Conditional Statements in React js

  • In React, you can use conditional statements inside JSX to render different components or content based on a condition. There are a few different ways to implement conditional statements in JSX, including using the ternary operator, the && operator, and the if statement.
  • Here's an example of using the ternary operator to render different components based on a condition:
function MyComponent({ isLoggedIn }) {
    return (
        <div>
            {isLoggedIn ? <p>Welcome back!</p> : <p>Please log in</p>}
        </div>
    );
}
  • In this example, the isLoggedIn prop is used to determine whether to render a "Welcome back!" message or a "Please log in" message. The ternary operator is used to conditionally render the appropriate message based on the value of isLoggedIn.
  • You can also use the && operator to conditionally render content based on a condition:
function MyComponent({ isLoggedIn }) {
    return (
        <div>
            {isLoggedIn && <p>Welcome back!</p>}
        </div>
    );
}
  • In this example, the Welcome back! message is only rendered if isLoggedIn is true. This works because the && operator returns the second operand only if the first operand is truthy.
  • Finally, you can use an if statement to conditionally render content:
function MyComponent({ isLoggedIn }) {
    if (isLoggedIn) {
        return <p>Welcome back!</p>;
    } else {
        return <p>Please log in</p>;
    }
}
  • In this example, the if statement is used to conditionally return different components based on the value of isLoggedIn.
  • Note that when using conditional statements in JSX, you must ensure that the return value of the component is a single element or a fragment. In the examples above, a single div element is used as the parent element for the conditional content.

No comments:

Post a Comment

Primitive Types in TypeScript

In TypeScript, primitive types are the most basic data types, and they are the building blocks for handling data. They correspond to simple ...