React.cloneElement() Method
The React.cloneElement() method is used 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 into the function.
Syntax:
React.cloneElement(
element,
[props],
[...children]
)
Example: In this example, we have used cloneElement to pass down the props.
Javascript
//App.js import React from 'react' ; import Button from './Button' ; import './styles.css' ; const App = () => { return ( <Parent> <Button /> <br /><br /> <Button /> </Parent> ) } const Parent = (props) => { let btn = 'w3wiki' ; return ( <div> {React.Children.map(props.children, child => { return React.cloneElement(child, { btn }, null ); // third parameter is null // Because we are not adding // any children })} </div> ) } export default App; |
Javascript
//Button.js import React from 'react' ; const Button=(props)=> { return ( <button> {props.btn } </button> ) } export default Button; |
Output:
What is the difference between createElement and cloneElement ?
This article will help us to gain knowledge of createElement and cloneElement and we will also learn them with code examples and their difference.
We will learn the following methods:
Table of Content
- React.createElement()
- React.cloneElement()
- Difference between createElement and cloneElement