Tuesday, November 19, 2024
Google search engine
HomeLanguagesHow to use React.cloneElement() function?

How to use React.cloneElement() function?

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]
)

The first argument is the element that we want to clone. The second argument will be additional props that we want to add with the element. And the third argument will be the children of cloned elements and children of the existing element will not be copied in cloned elements.

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

<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.

Creating 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: It will look like the following.

App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.

Javascript




import React from 'react';
class App extends React.Component {
    render() {
        return (
            <Parent>
                <Button />
                <br /><br />
                <Button />
            </Parent>
        )
    }
}
 
class Parent extends React.Component {
    render() {
        let btncolor = 'red';
        return (
            <div>
                {React.Children.map(this.props.children,
                    child => {
                        return React.cloneElement(child,
                            { btncolor }, null); //third parameter is null
                        // Because we are not adding any children
                    })}
            </div>
        )
    }
}
 
class Button extends React.Component {
    render() {
        return (
            <button style=
                {{ color: this.props.btncolor }}>
                Hello from GFG
            </button>
        )
    }
}
 
export default App


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:

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.

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments