ReactJS - Pass Props To Dynamic Children

In general, we pass the prop from parent to its child something like below:

// App.js
import ProfileForm from "../components/ProfileForm";

export default function App() {
  const profile = {
    firstName: "John",
    lastName: "Doe",
    age: 23
  };

  return (
    <div className="App">
      <ProfileForm {...profile} />
    </div>
  );
}

Here we are passing the profile object to ProfileForm child component, which is a very common pattern in react.

It becomes slightly challenging when the child is dynamic.

Let's update our example above:

// App.js
export default function App({ children }) {
  const profile = {
    firstName: "John",
    lastName: "Doe",
    age: 23
  };

  return <div className="App">{children}</div>;
}

Here we can see that as the child (here children) is dynamic, we cannot directly pass the profile object to the children.

For such situations, we can make use of reacts cloneElement api. Its syntax is below:

React.cloneElement(
  element,  // the element we are making clone of, in our example, its `children`
  [config],  // we can pass props as the 2nd argumanet, which will be merged with the existing props
  [...children]  // we can pass new children, which will replace existing children
)

Coming back to our example, we can update our App.js file as below:

// App.js
import React from 'react';

export default function App({ children }) {
  const profile = {
    firstName: "John",
    lastName: "Doe",
    age: 23
  };

  const childClone = React.cloneElement(children, profile)
  return <div className="App">{childClone}</div>;
}

This way we can pass props to dynamic children.

Thanks for your time.


Further Reading:

React - cloneElement