React Foundations · Rendering & JSX

Conditional rendering

Conditional rendering

A visitor is signed in; another is not. You want the page to say something different to each. In plain JavaScript you would reach for an if, but JSX has no place to put one.

You rarely need it. Because {} holds an expression, you can choose what to render with the operators JavaScript already gives you.

The ternary picks between two elements:

return <p>{loggedIn ? 'Welcome back!' : 'Please log in.'}</p>;

The logical AND renders something only when a condition is true, and renders nothing when it is false:

return <p>{hasError && 'Something went wrong.'}</p>;

Both are ordinary expressions, so they can appear anywhere a value can — inside an element, in an attribute, or as the whole return value. React renders whatever the expression evaluates to, and false, null, and undefined render nothing at all.

Your job is to render one of two messages based on a prop.

Challenge

The screen always says Please log in., even when someone is signed in. Export an App component from App.jsx that accepts a loggedIn prop and shows Welcome back! when it is true, or Please log in. when it is false.

The Test renders <App loggedIn={true} /> and reads the paragraph's text. The starter always prints Please log in., so the Test fails — pick the message with a conditional expression.

App.jsx
export function App() {
  return <p>Please log in.</p>;
}

No test run yet

The Test is hidden. Run it to check the Challenge — you only see the result, never the test source.