React: Signed in or not

Show different JSX for a signed-out and a signed-in visitor.

What to build

A status bar that changes with the user.

Requirements

  • Write Status({ user }). When user is null, return a div with the class status holding a button Sign in.
  • Otherwise return a div with the class status holding a p Signed in as NAME and a button Sign out.
  • App renders Status twice: with user={null} and with user="Mitu".

Constraints

Use an early return or the conditional operator.

Example

The first bar has only a Sign in button; the second says "Signed in as Mitu" with a Sign out button.

Why it works

The same component chooses its JSX from its props, so each place it is used shows the right state.

Hints

Hint 1

if (!user) return ...; then the signed-in JSX.

Hint 2

App renders the component twice, with user={null} and with a name.

Solution

Show one correct solution (try it yourself first)
function Status({ user }) {
  if (!user) {
    return (
      <div className="status">
        <button>Sign in</button>
      </div>
    );
  }
  return (
    <div className="status">
      <p>Signed in as {user}</p>
      <button>Sign out</button>
    </div>
  );
}

export default function App() {
  return (
    <div>
      <Status user={null} />
      <Status user="Mitu" />
    </div>
  );
}

Lesson: Conditional rendering →