Any React application usually consists of many different components. These components interact with each other. To make the components useful we need to pass data to the components.
Props in React
One way of passing data to the child component from the parent component is using props. In the case of normal HTML elements, we have attributes that we use for setting different element values such as the background color or the margins. This makes the HTML elements configurable by the user.
React also uses a similar concept using props. Since React components are custom HTML elements we can define attributes on the components while using them. For example, if we have a component called User, then we can use it as:
<User></User>
We can also define attributes on the User component. If we want to define an attribute called name then we can set it as:
<User name="Ashish"></User>
Instead of hardcoding the name we can use javascript variables as:
<User name={name}></User>
Here we have defined name attribute on the User component but could have used any other name.For example instead of name we could have used:
<User userName={userName}></User>
the attribute userName above is called Prop in React.
The next step is to access this attribute in the component function. We can access it in the component function by using the parameter in the function:
function User(props)
{
}
The props parameter above contains the userName property. We can access the username uisng props parameter as:
const name=props.userName
We can add more props in the User component as:
<User userName={name} age={age} location={location} ></User>
All these props will be available in User component:
const name=props.userName
const age=props.age
const location=props.location