Author -  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 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY