Props

React · Essentials · 12 min

Props are how components are configured and composed; nearly every component you write takes some.

Props are the inputs to a component. You pass them like HTML attributes, and React collects them into one object that is the function's first argument:

<Avatar person={{ name: "Lin" }} size={100} />

function Avatar({ person, size = 48 }) { ... }

Destructuring in the parameter list is the idiomatic style, and a default value (size = 48) applies when the prop is missing or undefined. Any JavaScript value can be a prop: strings, numbers, objects, arrays, functions and JSX.

The special `children` prop holds whatever you nest between a component's tags. It is how you build wrappers like cards, layouts and dialogs that don't need to know what's inside them:

<Card><Avatar person={p} /></Card>   // Card receives children

You can forward a bag of props with spread, <Avatar {...props} />, which is handy in thin wrappers; use it sparingly, as it hides what is being passed.

Props are read-only. A component must never modify its props; they belong to the parent. When something needs to change over time, that's state, which you'll meet shortly. When the parent re-renders with new props, the child simply renders again with the new values.

In TypeScript, describe props with a type: function Avatar({ size }: { size: number }), or a named type AvatarProps = {...}.

Example

function Avatar({ person, size = 48 }) {
  return (
    <img
      className="avatar"
      src={person.imageUrl}
      alt={person.name}
      width={size}
      height={size}
    />
  );
}

function Card({ title, children }) {
  return (
    <div className="card">
      <h2>{title}</h2>
      {children}
    </div>
  );
}

export default function Profile() {
  const person = { name: "Lin Lanying", imageUrl: "https://i.imgur.com/1bX5QH6.jpg" };
  return (
    <Card title="Scientist">
      <Avatar person={person} size={100} />
      <p>Materials scientist</p>
    </Card>
  );
}

Remember

  • Props arrive as one object; destructure them and give defaults in the parameter list
  • children is whatever is nested between the tags, enabling wrapper components
  • Props are read-only; values that change over time belong in state

Watch out for

  • Mutating a prop (e.g. props.items.push(x)): the parent owns that data and won't know it changed.

Check yourself

  1. Given function Badge({ label = 'New' }), what label does <Badge label={undefined} /> show?
  2. What does a Layout component receive in children for <Layout><Nav /><Main /></Layout>?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: react.dev/learn/passing-props-to-a-component