React JS Props

Props is a special keyword in React, which stands for properties and is being used for passing data from one component to another. But the important part here is that data with props are being passed in a uni-directional flow. ( one way from parent to child)

We can get more idea by looking at the below example. you can put this files in /src/components folder and put in /src/App.js file.

1. Parent component

Parent component
import React, { Component } from 'react'; import ReactTutorialChild from './components/ReactTutorialChild'; class ReactTutorialParent extends Component { render() { return( <div> <ReactTutorialChild name="Ramesh" /> </div> ); } } export default ReactTutorialParent;

Here, we have pass data "Ramesh" to our child component. so, we add one attribute name="Ramesh" into the . Now we have to get this attribute in child component.

2. Child component

Child component
import React, { Component } from 'react'; const ReactTutorialChild = props => { console.log(props); return <h1> Hello {props.name} </h1> } export default ReactTutorialChild;

In child component, we have used it as a functional component for a better idea of that. If you add both components in our exiting project and run that, then we can find Object > name: "Ramesh" in inspect element of our website. Browser shows Hello Ramesh.

Let's discuss in more detail,

Parent component

Parent component
class ReactTutorialParent extends Component { render() { return( <div> <ReactTutorialChild name="Ramesh" contry="India" /> </div> ); } }

Here, we passed this two data to child component.

Child component

Child component
const ReactTutorialChild = props => { console.log(props); return <h1> Hello {props.name}, you are from {props.contry}</h1> }

In child component, in console log you can find Object > { name:"Ramesh", contry:"India" } and browser shows Hello Ramesh, you are from India.

We can change keyword props as anything(eg. aaa, data, bbb, obj). Also, destructure props as per below code. this is ES6 feature.

Example
const ReactTutorialChild = ({name, contry}) => { return <h1> Hello {name}, you are from {contry}</h1> }

Child component as class component

Child component as class component
class ReactTutorialChild extends Component { console.log(this.props); render () { return <h1> Hello {this.props.name}, you are from {this.props.contry}</h1> } }

In this class component. you can use props as this.props. only diffent from functional component is this keyword.

In this way, We can pass data from parent component to child component as props.

 

← Previous

Next →