Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Conditional Rendering | Controlling Data & Content
Introduction to React

bookConditional Rendering

We can render components based on condition(s) using if-else statements or ternary operators.

For example, we can display different messages based on a variable. Consider, for example, we have a component that displays different UI based on the state of the loggedin state:

function Welcome(props) {
  if (props.loggedin == false) {
    return (
      <div>
        <p>Welcome new user. You can register now for free!</p>
        <button>Register</button>
      </div>
    );
  } else {
    return (
      <p>Welcome, {props.username}!</p>
    );
  }
}

We can pass the loggedin value as false:

root.render(<Welcome loggedin={false} />);

Note that we also enclose Boolean values in braces {}. The output should be something like this:

Now if we pass the value true into the component, the output will change:

root.render(<Welcome loggedin={true} username="Max Tegmark" />);

This time, we also passed the value "username" since I was required in the else block. This way, conditionals can be used to do simple and complex tasks.

It is up to you how you use it!

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 5. Kapittel 2

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Suggested prompts:

Still meg spørsmål om dette emnet

Oppsummer dette kapittelet

Vis eksempler fra virkeligheten

Awesome!

Completion rate improved to 2.7

bookConditional Rendering

Sveip for å vise menyen

We can render components based on condition(s) using if-else statements or ternary operators.

For example, we can display different messages based on a variable. Consider, for example, we have a component that displays different UI based on the state of the loggedin state:

function Welcome(props) {
  if (props.loggedin == false) {
    return (
      <div>
        <p>Welcome new user. You can register now for free!</p>
        <button>Register</button>
      </div>
    );
  } else {
    return (
      <p>Welcome, {props.username}!</p>
    );
  }
}

We can pass the loggedin value as false:

root.render(<Welcome loggedin={false} />);

Note that we also enclose Boolean values in braces {}. The output should be something like this:

Now if we pass the value true into the component, the output will change:

root.render(<Welcome loggedin={true} username="Max Tegmark" />);

This time, we also passed the value "username" since I was required in the else block. This way, conditionals can be used to do simple and complex tasks.

It is up to you how you use it!

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 5. Kapittel 2
some-alt