Ask Question

How to dynamically add a prop to a React child element

I am passing children to my React component and would like to dynamically add props to the children from the parent component.

Here is an example code:

<ParentComponent>
  <ChildComponent prop1="test" />
  <ChildComponent prop1="test2" />
</ParentComponent>

My ParentComponent looks like this:

import React from 'react';

const ParentComponent = ({ children }: React.PropsWithChildren<unknown>) => {
  return (
    <>
      {children} // here I would like to dynamically add props to those children
    </>
  );
};
ReactJavaScriptTypeScript

3914 views

Authorยดs Dominik Sumer image

Dominik Sumer

Last edited on

1 Answer available

Best answer

React comes with two very handy utils for this. It lets you iterate over the children and clone them to dynamically add props.

Here is an example for your ParentComponent:

import React from 'react';

const ParentComponent = ({ children }: React.PropsWithChildren<unknown>) => {
  return (
    <>
      {React.Children.map(children, (child) => {
        return React.cloneElement(child, {
          prop2: child.props.prop1 + '_suffix',
        });
      })}
    </>
  );
};
๐ŸŽ‰
1