Sometimes, we want to pass props to nested child components in React.
In this article, we’ll look at how to pass props to nested child components in React.
Pass Props to Nested Child Components in React
To pass props to nested child components in React, we can use the React.Children.map
and the React.cloneElement
methods to pass props to child components.
For instance, we write:
import React from "react";
const Child = ({ doSomething, value }) => (
<button onClick={() => doSomething(value)}>Click Me</button>
);
const Parent = ({ children }) => {
function doSomething(value) {
console.log("do something: ", value);
}
const childrenWithProps = React.Children.map(children, (child) => {
if (React.isValidElement(child)) {
return React.cloneElement(child, { doSomething });
}
return child;
});
return <div>{childrenWithProps}</div>;
};
export default function App() {
return (
<Parent>
<Child value={1} />
<Child value={2} />
</Parent>
);
}
We create the Child
component that takes a few props and renders a button which runs doSomething
when we click on it.
Then we create the Parent
component that takes the children
prop.
We pass the props into the children
components by calling React.Children.map
method with children
and a callback that takes the child
parameter.
And then we check if child
is a valid component with React.isValidElement
.
And if it is, then we return the element with the props passed into it with:
React.cloneElement(child, { doSomething })
Otherwise, we return child
as is.
Then we returned child components with the props passed in are assigned to childrenWithProps
.
And finally, they’re rendered in the div.
In App
, we add the Parent
component with the Child
components inside it.
Therefore, when we click each button, we see the value
prop value passed into it logged.
Conclusion
To pass props to nested child components in React, we can use the React.Children.map
and the React.cloneElement
methods to pass props to child components.