React, how to transfer props to child components

By

Learn how to forward all the props a React component receives from its parent straight down to its own children using the JavaScript spread operator.

~~~

To transfer all the props a React component receives down to its child components, spread the props object in JSX: <ChildComponent {...props} />. Every prop gets forwarded, whatever its name.

Suppose you have a hierarchy of components, where you pass props from a top component, and you need to pass those props unaltered to a children. It happens many times, and you don’t really want to do like this:

const IntermediateComponent = (props) => {
  return (
    <ChildComponent prop1={props.prop1} prop2={props.prop2} />
  )
}

Listing every prop by hand is tedious, and it breaks the moment the parent starts sending a new prop. You’d have to update the intermediate component every time, even though it doesn’t use those props at all.

Instead, you want to pass all the props, regardless of their name.

You can do so with the spread operator:

const IntermediateComponent = (props) => {
  return (
    <ChildComponent {...props} />
  )
}

This syntax is much easier to the eye, much less error prone, and it allows flexibility, since you don’t need to change the props names or add props in the intermediate component when you change them.

The spread takes every property of the props object and passes each one as an individual prop. If the parent renders <IntermediateComponent user={user} theme='dark' />, the child receives user and theme, exactly as if you had written them out.

What if the component uses some props itself?

Often the intermediate component consumes a couple of props and should forward the rest. Destructure what you need, and collect the remainder with a rest element:

const Panel = ({ title, ...rest }) => {
  return (
    <section>
      <h2>{title}</h2>
      <PanelContent {...rest} />
    </section>
  )
}

title stays here, everything else flows down. This also prevents forwarding props the child has no business receiving.

Watch the order

You can combine the spread with props you set explicitly, and order matters. The last one wins:

<ChildComponent {...props} theme='dark' />

Here theme is always 'dark', even if props contains a theme. Flip the order and the incoming prop overrides your default instead.

One pitfall: spreading everything onto a plain HTML element, like <div {...props}>. Any prop that isn’t a valid DOM attribute triggers a React warning about unknown props in the console. The rest element pattern above is the fix, spread only what belongs on the element.

Tagged: React · All topics
~~~

Related posts about react: