Rendering and data flow

Render a condition

Use normal JavaScript to choose which JSX a component returns.

Use ordinary JavaScript conditions to choose JSX. You are not learning a new template language here. If you can write an if in JavaScript, you can write conditional UI in React.

Return early when the whole screen state changes:

function Account({ user }) {
  if (!user) {
    return <LoginForm />
  }

  return <Dashboard user={user} />
}

Pass user={null} and you get the login form. Pass a user object and you get the dashboard.

Use a ternary for two small alternatives:

<p>{saved ? 'Saved' : 'Unsaved changes'}</p>

Use && when the false branch should render nothing:

{error && <p role="alert">{error}</p>}

Set error to 'Network failed' and the alert appears. Set it to '' and nothing renders.

Be careful with numbers. items.length && <List /> renders 0 for an empty list. Write items.length > 0 && <List /> when that is the real condition.

Do not hide inaccessible markup with CSS when it should not exist in the interaction tree. Conditional rendering can remove it from both the DOM and accessibility tree.

Avoid deeply nested ternaries. Calculate a named variable or extract a component when the states become hard to scan.

Extracting a small component is often clearer than a long chain of conditions. A TaskListStatus component can own the loading and error branches while the parent stays readable.

Switch statements also work when you prefer them over early returns. The important part is that normal JavaScript control flow picks the JSX, not a special React API.

Nullish coalescing helps pick fallback UI: {message ?? 'No message yet'} renders the string when message is null or undefined.

Render loading, error, empty, and success states for one list. Make each state explicit and reachable in a test.

Lesson completed