In this article, we are going to learn about Props in React JS.
Props in ReactJS
Props stands for Properties. In react application props plays an important role which allow us to pass information from one component to another (Parent Component to Child Components). Props basically are objects which can be used inside the component. The props are immutable, so we can't change them inside the component. These attributes are present in the component as this.props , we need to add props to reactDOM.render menthod in the main.js file of ReactJs project and then use it inside the component.
Using Props in React
For using props in react we follow some steps to implement props. These are,
- An attribute and its value
- Pass it to Child Component from Parent Component by using props
- Render the props data.
An Attribute and Its Value
We can assign value to React Components while calling. Will name the attribute name as text and assign string type to it.
<Child text={βIβm the child Componentβ} />
After adding the data, we need to pass the data through props.
Passing Data using Props (Parent to Child)
Now let's take the "Child Component" string and pass it with props. Passing props in a simple way, just add props as if we were passing the argument to functions.
const Child = (props) => {
return <p>Child </p>;
};
Renders Props Data
Need to render props as we already passed it to the child component as an argument.
const Child = (props) => {
return <p>{props.text}</p>;
};
class Parent extends Component {
render() {
return (
<h1>
the parent component.
<Child text={"Child Component"} />
<Child text={"Child Component"} />
<Child text={"Child Component"} />
</h1>
);
}
}
Every child component now renders its prop data. This is how we pass props from Parent to Child Component.
Now let's think of a scenario, we need to pass some default information by using props.
React provides us something called as defaultprop.
DefaultProps
defaultProps is a method that allows us to store any amount of information for a given class. And that information can be accessed from anywhere within that particular class. Any information you add inside defaultProps will be added as a prop to this class.
import React from 'react';
import ReactDOM from 'react-dom';
// Component
class SampleClass extends React.Component{
render(){
return(
<div>
{/* using default prop - title */}
<h1>This is {this.props.title}'s WebPage!</h1>
</div>
);
}
}
// Creating default props for
// SampleClass Component
SampleClass.defaultProps = {
title: "GeeksforGeeks"
}
ReactDOM.render(
<SampleClass />,
document.getElementById("root")
);
Happy Learning :)