Clue Mediator

Props in React JS

📅July 17, 2019

This article is all about the understanding of the props in React JS. State and Props are used to control the data flow in the react application. With the help of them we can render the component with dynamic data.

What is props in react, Understanding of State and Props in React JS, Communicate between two component using props. How to pass props from one component to another in React JS.

Demo & Source Code

Github Repository

Props in React JS

  1. What is Props and why we need Props?
  2. Example

1. What is Props and why we need Props?

The props is nothing but plain javascript object. Props are immutable so we can not change the data of props in React JS.

As you know if you want to change the value inside the component then you are going to use state variable and render the component based on the state variable. But let’s say if you want to pass data from one component to another component then you have to use props.

You can refer the below link for understanding of state.
State in React JS

You can pass data in React Components by defining custom HTML attributes in which you can assign data with JSX syntax. You can pass data in different formats like string, integer, boolean, object, array, etc and for that you have to use the curly braces.

2. Example

Here we have taken simple example where we have created Greeting component and use it in multiple components by passing different values as props.

Greeting.js

import React, { Component } from 'react';

class Greeting extends Component {
  render() {
    return <h1>{this.props.greeting}</h1>;
  }
}

export default Greeting;

We have created two components and import the Greeting component in both file. Please check below codes for same.

Home.js

import React, { Component } from 'react';
import Greeting from './Greeting';

class Home extends Component {
  render() {
    return <div>
      <Greeting greeting={"Welcome to home page!"}/>
      <p>Here is the testing page created by Clue Mediator.</p>
    </div>
  }
}

export default Home;

About.js

import React, { Component } from 'react';
import Greeting from './Greeting';

class About extends Component {
  render() {
    const title = "About Page";
    return <div>
      <Greeting greeting={title} />
      <p>This is testing page</p>
    </div>
  }
}

export default About;

That’s it about the props for now. We will cover more articles where we explain you how to communicate between two components with real example.