How to pass a function as props to React Children?
Solution 1:
function Mouse({hovered}) {
return null;
};
function Navbar({toggleHover}) {
return <div onMouseEnter={toggleHover}>Hover on me</div>
};
function Footer({toggleHover}) {
return <div onMouseEnter={toggleHover}>Hover on me</div>
};
function Child({toggleHover}) {
return <div onMouseEnter={toggleHover}>I am child, hover on me</div>
};
function Layout({ preview, children }) {
const [hovered, setHovered] = React.useState(false);
function toggleHover() {
console.log("hovered");
setHovered(!hovered);
}
const childrenWithProps = React.Children.map(children, (child) => {
if (React.isValidElement(child)) {
return React.cloneElement(child, { toggleHover: toggleHover });
}
return child;
});
return (
<div>
<Mouse hovered={hovered} />
<div>
<Navbar toggleHover={toggleHover} />
<main>{childrenWithProps}</main>
<Footer toggleHover={toggleHover} />
</div>
</div>
);
}
function Parent() {
return (
<div>
<Layout>
<Child />
<Child />
<Child />
</Layout>
</div>
)
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<Parent />,
rootElement
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
<body>
<div id="root"></div>
</body>
Problem is on function childrenWithProps
, especially in React.cloneElement
props argument. In your example you are using value toggleHover
which essentially transforms into toggleHover: toggleHover
.
To make it work you need to transform passed props into this: children_prop_name: toggleHover
.
A more detailed example:
Function handling children properties:
const childrenWithProps = React.Children.map(children, (child) => {
if (React.isValidElement(child)) {
return React.cloneElement(child, { toggleProp: toggleHover });
}
return child;
});
A child component:
function Child({toggleProp}) {
return <div onHover={toggleProp}>Click</div>
}