React: Cloning elements with React.cloneElement()

Posted on

in

,

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

Your email address will not be published. Required fields are marked *

About me

Mark Wong is a front end developer with 10+ years experience. Most of his knowledge of HTML5, CSS and Js is self taught.

Calendar

May 2024
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031