← React Beginner Questions - Set 2 Q20

What is conditional rendering in React?

React Beginner Questions - Set 2

No template language: conditions are plain JavaScript inside JSX. Three forms cover almost every case.

Example

export default function Inbox({ messages, isLoading, error }) {
  // 1. Early return for a whole different screen
  if (isLoading) return <p>Loading…</p>;
  if (error) return <p role="alert">{error}</p>;

  return (
    <section>
      {/* 2. Ternary when both branches render something */}
      <h2>{messages.length ? `${messages.length} unread` : 'Inbox zero'}</h2>

      {/* 3. Logical AND when the false branch renders nothing */}
      {messages.length > 100 && <p>Consider archiving older threads.</p>}

      <ul>
        {messages.map(m => <li key={m.id}>{m.subject}</li>)}
      </ul>
    </section>
  );
}

What to notice

← Back to the question list