How to use the react cloneElement method
In this tutorial, we are going to learn about how to use the react.cloneElement() method with the help of examples.
react.cloneElement()
The react.cloneElement() method helps us to clone and return a specified react element.
we can also pass additional props to the cloned react element.
The react.cloneElement()
method accepts three arguments.
-
element : Element you want to clone.
-
props : props you need to pass to the cloned element.
-
children : we can also pass children to the cloned element (passing new children replaces the old children).
Let’s see an example:
import React from "react";
// child component
function Button(props) {
return <button style={{color: props.color}}>{props.name}</button>;}
function Parent(props) {
const updateWithprops = React.Children.map(props.children, (child, i) => { // props return React.cloneElement(child, { color: "red" }); });
return <div>{updateWithprops}</div>;
}
function App() {
return (
<div className="App">
<Parent>
<Button name="Yes" /> <Button name="No" /> </Parent>
</div>
);
}
In the above example, we have used React.children.map()
method to iterate over the props.children
array then we passed a color
prop to the each child
element using the React.cloneElement()
method.
Inside the Button
component we accessed color prop using props.color
.
Note: The cloned element contains original element props with new props.
Output: