React Conditionals Tutorial

In this tutorial, you will learn about conditional rendering in React

What is React Conditional Rendering?

  1. React conditionals allow you to render different content based on certain conditions or states.
  2. They are very useful for creating dynamic and engaging user interfaces.

Types of Conditional Rendering

There are two main ways to implement conditional rendering in React

  1. Inline if-else statements: This is the simplest way to conditionally render content. You can use an if-else statement to render different elements based on a condition.
  2. Ternary operators: Ternary operators are a more concise way to write inline if-else statements. They take three arguments: a condition, a value to return if the condition is true, and a value to return if the condition is false.
function Button() {
const isLoggedIn = true;

if (isLoggedIn) {
    return <button>Log out</button>;
} else {
    return <button>Log in</button>;
}
}
  

This component will render a "Log out" button if the user is logged in, or a "Log in" button if the user is not logged in.

function Button() {
const isLoggedIn = true;

return (
    <button>{isLoggedIn ? 'Log out' : 'Log in'}</button>
);
}
  

This component is equivalent to the previous example, but it uses a ternary operator to write the if-else statement in a more concise way.

You can also use conditionals to render different components. For example, the following component renders a different greeting depending on the user's name:

function Greeting({ name }) {
    if (name === 'Mike') {
      return <div>Hello, Mike!</div>;
    } else {
      return <div>Hello, {name}!</div>;
    }
  }
  

This component can be used like this

<Greeting name="Mike" />

You can also use conditionals to control the flow of your application.

function LoginOrRegisterForm() {
const isLoggedIn = false;

if (isLoggedIn) {
    return <LoginForm />;
} else {
    return <RegisterForm />;
}
}
  

Render the above component and you will notice the changes in your page.