const UserCard = ({ name, children }) => {
return (
<div>
<p>Name: {name}</p>
{children}
</div>
)
}
const UserIcon = ({ profilePic }) => {
return <img src={profilePic} alt="profile" />
}
function App() {
return (
<div>
<UserCard name="Ranjeet">
<UserIcon profilePic="image.jpg" />
</UserCard>
</div>
)
}
export default App
import React, { Children, isValidElement, cloneElement } from 'react';
const Child = ({ doSomething, value }) => (
<div onClick={() => doSomething(value)}>Click Me</div>
);
function Parent({ children }) {
function doSomething(value) {
console.log('doSomething called by child with value:', value);
}
render() {
const childrenWithProps = Children.map(children, child => {
// Checking isValidElement is the safe way and avoids a TS error too.
if (isValidElement(child)) {
return cloneElement(child, { doSomething })
}
return child;
});
return <div>{childrenWithProps}</div>
}
};
ReactDOM.render(
<Parent>
<Child value="1" />
<Child value="2" />
</Parent>,
document.getElementById('container')
);