Open In App

How to pass props to ReactJS component that wrapped in variable ?

To pass props to a React JS component that is wrapped in a variable we have to create some copy of the component that can be modified. As we can’t access the props of that component and pass a required argument we can clone it to make the required element and use it in our application.

Props: Props means properties. Prop is an argument that we pass from the parent component to the child component in ReactJS through the HTML attribute.



Prerequisites:

Approach:

To pass the prop in the React JS component wrapped in a variable we will use React.cloneElement method to create a copy of it. While cloning the component we can have additional modifications e.g. prop and make the required element.

Steps to Create React Application:

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



npx create-react-app projectname

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

cd projectname

Project Structure:

 

Example: This example uses React.cloneElement method to pass props to React JS component wrapped in variable.




// Filename - App.js
 
import React from "react";
import Program from "./Program";
 
const App = () => {
    let c = <Program />;
 
    // Here passed props - {name1: "C++", name2: "JAVA"}
    const p = React.cloneElement(c, {
        name1: "C++",
        name2: "JAVA",
    });
    return <>{p}</>;
};
 
export default App;




// Filename - Program.js
 
import React from "react";
 
const Program = (props) => {
    return (
        <>
            <h1>
                My favourite programming language is
                {props.name1}
            </h1>
            <h1>
                Another favourite programming language is
                {props.name2}
            </h1>
        </>
    );
};
 
export default Program;

Steps to Run your Application: First, go to the root directory and then run the application with this command.

npm start

Output: This output will be visible on the http://localhost:3000/ on the browser window.


Article Tags :