by Sai gowtham

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:

react-clone-element-example

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course