DocsLearn

Props and children

A component gets what it shows from the one that uses it: values as props, and content as children.

In this lesson

  • how props reach a component, and how defaults work;
  • how a component shows what is put inside it;
  • how to pass the rest of the props on to an element inside.

Props

import { useState } from "react";
import { Button } from "@/components/ui/button";

function Meter({ value, max = 10, label }) {
  return (
    <div className="grid gap-1">
      <span className="text-sm">{label}: {value} of {max}</span>
      <div className="h-2 rounded-full bg-muted">
        <div className="h-2 rounded-full bg-primary" style={{ width: `${(value / max) * 100}%` }} />
      </div>
    </div>
  );
}

export default function App() {
  const [sold, setSold] = useState(3);
  return (
    <div className="grid gap-3">
      <Meter label="Tickets sold" value={sold} />
      <Button variant="secondary" onClick={() => setSold((n) => Math.min(10, n + 1))}>Sell one</Button>
    </div>
  );
}
  • Props follow the one that gave them. sold changes, App draws again, and Meter with it.
  • Defaults (max = 10) apply only when the prop isn’t given, or given undefined. null counts as given.
  • A component never changes its props. What should change is state, in the component that owns it, handed down as a prop and changed through a function it hands down too: onChange={setSold}.

Children

What is put between a component’s tags arrives as children:

function Card({ title, children }) {
  return (
    <section className="grid gap-2 rounded-xl border p-4">
      <h3 className="font-semibold">{title}</h3>
      {children}
    </section>
  );
}

export default function App() {
  return (
    <Card title="Opening hours">
      <p>Tuesday to Sunday, from 7 am.</p>
      <p className="text-sm text-muted-foreground">Closed on public holidays.</p>
    </Card>
  );
}

Passing props on

A component that wraps an element takes what it uses itself and passes the rest on, so whoever uses it can give the element anything it takes:

import { cn } from "cn";

function Field({ label, className, ...rest }) {
  return (
    <label className="grid gap-1 text-sm">
      {label}
      <input className={cn("rounded-md border px-3 py-1.5", className)} {...rest} />
    </label>
  );
}

export default function App() {
  return (
    <div className="grid gap-3">
      <Field label="Email" type="email" placeholder="you@example.com" />
      <Field label="Code" maxLength={6} className="font-mono tracking-widest" />
    </div>
  );
}

type, placeholder and maxLength reach the <input> without Field naming them.

Next: show data that comes from the server, in Loading data.

View as Markdown