Use this to copy elements and give them different props or add new ones.
import React from "react";
const ButtonContainer = (props) => {
let newProp = {
backgroundColor: "yellow",
textColor: 'black',
}
return (
<div>
{React.Children.map(props.children, child => {
return React.cloneElement(child, {newProp}, null)
})}
</div>
)
};
const Button = (props) => {
return <button
style={{
color: props.newProp.textColor,
backgroundColor: props.newProp.backgroundColor
}}>Read more</button>
}
function App() {
return (
<ButtonContainer>
<Button />
</ButtonContainer>
)
}
export default App
We have a Button which accepts the props textColor and backgroundColor. Then we have ButtonContainer which clones it’s children (in this case Button) but we can give it new props to create variations.
Leave a Reply