React allows us to pass information to a Component (from a parent component to a child component) using something called props (short for properties). Props is basically an object which is available for all the React components. Props are read only and cannot be modified by the component to which it belongs.
Passing and Accessing props: We can pass props to any component as we declare attributes for any HTML tag. Have a look at the below code snippet:
<Welcome fullName = "Harsh Agarwal" />
In the above code snippet, we are passing a prop named fullName to the component named Welcome. This prop has the value “Harsh Agarwal”. Let us now see how can we access this prop (property).
For a React component, props object will store the prop as key : value pairs and it will look as shown below. fullName is the key and “John Wick” is the value.
props = { fullName: "Harsh Agarwal" }
In case of functional components, we can access a prop value as shown below.
props.propName;
Example:
Javascript
import React from "react" ; import ReactDOM from "react-dom" ; /* Below given code will create a functional component called Welcome. This component takes one prop called fullName and displays a welcome message to the user. */ function Welcome(props) { return ( <div> <h1>Hello {props.fullName}</h1> <h2>Welcome to neveropen</h2> </div> ); } /* Below given code will render the HTML returned by the Welcome component inside the HTML element for which the id is "root" */ ReactDOM.render( <Welcome fullName= "Harsh Agarwal" />, document.getElementById( "root" ) ); |
Output:
The Complete list of Props are listed below:
- ReactJS | Methods as Props
- ReactJS | PropTypes
- ReactJS | Props – Set 1
- ReactJS | Props – Set 2
- Unidirectional Data Flow
- ReactJS | State in React
- ReactJS | State vs props
- ReactJS | Implementing State & Lifecycle