How to use the react cloneElement method

How to use the react cloneElement method

In this post we will give you information about How to use the react cloneElement method. Hear we will give you detail about How to use the react cloneElement methodAnd how to use it also give you demo for it if it is necessary.

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 componentfunction 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:

Hope this code and post will helped you for implement How to use the react cloneElement method. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US