Conteúdo do curso
Immersion in React: Comprehensive Course for Beginners
Sobre a Aula

Using Ternary Operators for Conditional Rendering

Hello, students! In the previous topic, we learned about conditional rendering based on states.

Today, let’s explore the use of ternary operators for conditional rendering.

What is a Ternary Operator?

The ternary operator is an expression that can be used to evaluate a boolean expression and return a different value depending on the result of the evaluation.

The syntax of the ternary operator is as follows:

condition ? value_if_true : value_if_false

For example, the following ternary operator returns “Yes” if the age variable is greater than 18 and “No” otherwise:

age > 18 ? "Yes" : "No"

How to Use Ternary Operators for Conditional Rendering

We can use ternary operators to conditionally render elements or content.

For example, the following code renders an h1 with the message “Welcome!” if the isLoggedIn variable is true and an h1 with the message “You are not logged in.” otherwise:

const isLoggedIn = true;

const App = () => {
  return (
    <div>
      {isLoggedIn ? (
        <h1>Welcome!</h1>
      ) : (
        <h1>You are not logged in.</h1>
      )}
    </div>
  );
};

Other Possibilities

In addition to rendering elements, we can also use ternary operators to render dynamic content.

For example, the following code renders the user’s name if the name variable is defined and the message “User undefined” otherwise:

const name = "John";

const App = () => {
  return (
    <div>
      {name ? (
        <h1>Hello, {name}!</h1>
      ) : (
        <h1>User undefined.</h1>
      )}
    </div>
  );
};

Conclusion

Ternary operators are a powerful tool that can be used to conditionally render elements or content.

By learning to use ternary operators, you can make your React components more dynamic and reactive.

I hope you’ve understood how to use ternary operators for conditional rendering.

Hook for the Next Module

In the next module, we will learn about lists in React. We’ll learn how to render data lists and how to use keys in lists. I hope you’re excited to learn more about lists in React!

Until then, keep studying!

Entrar na conversa
Rolar para cima