How to pass props to ReactJS component that wrapped in variable ?
Last Updated :
13 Nov, 2023
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.
Javascript
import React from "react" ;
import Program from "./Program" ;
const App = () => {
let c = <Program />;
const p = React.cloneElement(c, {
name1: "C++" ,
name2: "JAVA" ,
});
return <>{p}</>;
};
export default App;
|
Javascript
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...