React.cloneElement()
React.cloneElement() is a utility function within the React Top-Level API designed for manipulating elements or components. Essentially, it duplicates and provides a new element or component, utilizing its first argument as the starting point. This proves beneficial when there is a need to append or alter the props of a parent component.
Syntax:
React.cloneElement(
element,
[props],
[...children]
)
As we can observe the syntax of React.cloneElement() consists of three things, it can add, modify or extend the functionality of children’s properties.
- element: It is the name of the element that is to be cloned.
- [props]: Props that are to be added to the original element.
- […children]: The children of the cloned object.
Example: The example showcases a Parent component using React.cloneElement to add a new “color” prop to a Child component rendered as its child via props.children.
Javascript
import React from "react" ; function Parent(props) { const newChild = React.cloneElement( props.children, { color: "green" } ); return <div>{newChild}</div>; } function Child(props) { return ( <div style={{ backgroundColor: props.color }}> <h1>{props.title}</h1> <p>{props.text}</p> </div> ); } export default function App() { return ( <Parent> <Child title= "Hi, This is w3wiki! " text= "This is the child component" /> </Parent> ); } |
Output: This code will be a Child component with a green background color, in addition to its original props.
Difference between React.cloneElement and this.props.children
React.cloneElement and this.props.children are functionalities within React that play distinct roles in manipulating React components and elements. Although both are employed for this purpose, they are utilized in different contexts. Let’s delve into the specifics of each.
Table of Content
- React.cloneElement()
- this.props.children
- Difference between React.cloneElement and this.props.children.
Contact Us