How to pass data from component to component ReactJs

Learn how to pass data (values) from ReactJS Component to another component. In Reactjs it is called props. Props are the values you passed from component to component. Props are immutable data. You can easily pass data from parent Reactjs Component to child component using props.

Step 1: Create Parent Component (Component 1)

Here we are creating sample component which is the parent component named as "MyParents". We use this component to pass data to second component named as "FirstChildren ". Second component will be created in step 2.

import React, { Component } from 'react';
class MyParents extends Component {
  constructor(props){
    super(props)
    this.state = {
      firstChildName: "Charlie",
      firstChildAge:15
    }
  }
  render() {
    return (
      <div className="App">
        <h2> Parent Component </h2>
      </div>
    );
  }
}

Step 2: Create Child Component (Component 2)

Next create second component that you want to have values or props from another component.

class FirstChildren extends Component {
  constructor(props){
    super(props)
  }

  render() {
    return (
      <div className="App">
        <h2> Child Component </h2>
        <p>
          Name:
        </p>
        <p>
          Age:
        </p>
      </div>
    );
  }
}
    

Step 3: Include component 2 on component 1 and pass values (Props)

In order to pass values from first component to second component we have to include second (child) component inside the first (parent) component.

class MyParents extends Component {
  constructor(props){
    super(props)
    this.state = {
      firstChildName: "Charlie",
      firstChildAge:15
    }
  }
  render() {
    return (
      <div className="App">;
        <h2>; Parent Component </h2>;
        <FirstChildren
          name = {this.state.firstChildName}
          age = {this.state.firstChildAge}
        />
      </div>;
    );
  }
}

Step 4: Accessing passed values (props) from component 2

All the values pass from parent component stored on props variable of child component or component 2. You can access that variable using "this.props" . See below code for more clarification

class FirstChildren extends Component {
  constructor(props){
    super(props)
  }

  render() {
    return (
      <div className="App">
        <h2> Child Component </h2>
        <p>
          Name: {this.props.name}
        </p>
        <p>
          Age: {this.props.age}
        </p>
      </div>
    );
  }
}

Feel free to leave a component.

Add a Comment

You have to agree to the comment policy.