VOOZH about

URL: https://www.geeksforgeeks.org/reactjs/how-to-use-react-cloneelement-function/

⇱ How to use React.cloneElement() function? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to use React.cloneElement() function?

Last Updated : 2 Nov, 2023

We can use React.cloneElement() method when a parent component wants to add or modify the props of its children. The React.cloneElement() function creates a clone of a given element, and we can also pass props and children in the function.

The resultant element would have the initial element's props mixed in shallowly with the new props. Existing children will be replaced by new children. The original element's key and the ref will be preserved.

Syntax

React.cloneElement(
 element,
 [props],
 [...children]
)

Parameters:

  • Element: the element that we want to clone.
  • [props]: The additional props that we want to add to the element.
  • [...children]: The children of cloned elements and children of the existing element will not be copied into cloned elements.

Cloning an element with React.cloneElement() is almost the same as this:

<element.type {...element.props} {...new_props}>
 {new_children}
</element.type>

However, it also preserves refs. This means you won't unintentionally steal a ref from your ancestor if you have a child with one. The same ref will be assigned to your new element.

Steps to create React Application

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure:

👁 Image

Example: This example shows the inplementation of React.cloneElement() to clone the button element with additional props in the parent element.

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:

👁 Screenshot-from-2023-10-20-15-37-58


Explanation: As we can see from the above code Parent component is adding new props for the text color to the child (Button) component using React.cloneElement() method.

Comment