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

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2021 (Beginner + Advanced)
JavaScript - The Complete Guide 2021 (Beginner + Advanced)
64,026 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)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
152,857 students enrolled
48.5 hours of video content
View Course