Components and JSX

Components are React's unit of composition. JSX expresses UI structure as readable, testable code.

Functional components

A React component is a JavaScript function whose name starts with a capital letter (so JSX distinguishes it from lowercase HTML tags like <div>) and returns JSX. Destructuring props in the parameter list makes the component's inputs immediately visible:

function Badge({ label, tone = "info" }) {
  // Props are read-only inputs; never mutate `label` or `tone`
  return <span className={`badge bg-${tone}`}>{label}</span>;
}

Props contract

Props are read-only input contracts passed from parent to child. Never mutate a prop object inside a child component; if a child needs to trigger a change, pass a callback prop such as onSelect so the parent updates its own state.

JSX rules

Because JSX compiles to JavaScript expressions, a few syntax rules differ from plain HTML:

  • Single root element: Return one root element or wrap siblings in a Fragment (<>...</>) to avoid extra DOM wrappers.
  • DOM property names: Use camelCase attributes like className and htmlFor instead of class and for.
  • Close every tag: Self-closing tags such as <img /> and <input /> must include the trailing slash.

Composition patterns

Prefer composition over inheritance by passing nested elements through the special children prop or dedicated slot props (such as header and footer). This keeps wrapper components decoupled from the specific content rendered inside them:

function Card({ title, children }) {
  return (
    <section className="card p-3">
      <h3>{title}</h3>
      <div>{children}</div>
    </section>
  );
}

Professional tips

Structure components so they stay easy to test and refactor:

  1. Keep components focused and cohesive—split a component when it mixes unrelated layout and data-fetching concerns.
  2. Extract stateful logic into custom hooks when complexity rises.
  3. Name components by business intent (InvoiceSummary), not visual style only.

Practice

Build a reusable card system with header, body, and action slots, then use it in three different contexts.