React JS Tutorial - Props

In this tutorial, we will learn about props in React. As a component-based library, React divides the user interface into small, reusable pieces. However, in some cases, these components need to communicate with each other, and that's where props come in.

"Props" is a special keyword in React that stands for "properties." It is used to pass data from one component to another. In this tutorial, we will learn how to use props to pass data between components.

Let's start by opening the Post Component and the Student Component in our project. In this example, the Student Component is the child component, and the Post Component is the parent component.

We will now pass some properties from the parent component to the child component. Go to the Post Component and add the following code:


<Student name="Smith John" email=smith@gmail.com phone="1234567890" />

Next, we need to access these properties in the Student Component. Go to the Student Component and add the following code:


import React, { Component } from 'react'

class Student extends Component {
render() {
return (
<div>
<h3>Student Details</h3>
<p>Name: {this.props.name} </p>
<p>Email: {this.props.email} </p>
<p>Phone: {this.props.phone}</p>
</div>
)
}
}

export default Student;

Let's check the result. Switch to your browser, and you should see the Student Component with the passed properties.

There is another way to use props. Let's go back to the project and modify the Student Component by adding the following code:


import React, { Component } from 'react'

class Student extends Component {
render() {
const {name,email,phone} = this.props;
return (
<div>
<h3>Student Details</h3>
<p>Name: {name} </p>
<p>Email: {email} </p>
<p>Phone: {phone}</p>
</div>
)
}
}

export default Student;

Save the file and let's see the result. Switch to your browser, and you should see the Student Component with the passed properties.

Now, let's use the Student Component with different properties. Go to the Post Component and add the following code:


<Student name="Peter" email=peter@gmail.com phone="1209876543" />

Save the file and switch to your browser. You should see the Student Component with different properties.

This demonstrates how to use props in React components. By following these steps, you can pass data between components and reuse them throughout your application.