Props: Props means properties. Props is an argument that we pass from the parent component to the child component in ReactJS through the HTML attribute. You can refer to this article to know more about props: https://www.geeksforgeeks.org/reactjs-props-set-1/
Now we will see how to pass props to the ReactJS component that is wrapped in variables. Here we have used React.cloneElement() method to get it. The whole process is shown below. Here the whole process is shown by creating the application.
Creating 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 folder Structure: It has to look like this.
App.js: Here the component <Program/> is wrapped in the “c” variable. Then the React.cloneElement() method used here. This method is used to create the clone of the element that will be given as an argument, also here we can pass props and children as arguments. Here variable “c” is passed as an element in React.cloneElement() method for cloning, also passed props {name1: “C++”, name2: “JAVA”}.
You can refer to this article to know more about React.cloneElement(): https://www.geeksforgeeks.org/how-to-use-react-cloneelement-function/
Note: Before using the component, you must import the component file
Javascript
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; |
Program.js: Here the props are passed from App.js
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: