How to pass data from child component to its parent in ReactJS?

Props can be used to pass static values or the results of dynamic expressions to parent components.

Create React App

Type the following command to create a new react app:

npx create-react-app demo

Now, go to the project folder:

cd demo

Now, update default App.js with below code snippet

src\App.js

import React, { Component } from 'react';
import Area from './components/Area';
import Parameter from './components/Parameter';
 
class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      data: 0,
      len: 40,
      bre: 50
    }
    this.updateState = this.updateState.bind(this);
  }
 
  updateState(calculation) {
    if(calculation == "Area")
    {
      this.setState({data: this.state.len * this.state.bre})
    }
    else
    {
      this.setState({data: 2 * (this.state.len + this.state.bre)})
    }
  }
 
  render() {
    return (
      <div>
        Calculation: {this.state.data}
        <Area update={this.updateState} />
        <Parameter update={this.updateState} />
      </div>
    )
  }
}
 
export default App;

Create new Area component and type out the below code into Area.js

src\components\Area.js

import React, { Component } from 'react';
 
class Area extends Component {
  render() {
    return (
      <div>
        Area:
        <button onClick={() => this.props.update('Area')}>
          Area
        </button>
      </div>
    );
  }
}
 
export default Area;

Create new Parameter component and type out the below code into Parameter.js

src\components\Parameter.js

import React, { Component } from 'react';
 
class Parameter extends Component {
  render() {
    return (
      <div>
        Parameter:
        <button onClick={() => this.props.update('Parameter')}>
          Parameter
        </button>
      </div>
    );
  }
}
 
export default Parameter;

The Area and Parameter components are passing the value from child component to parent component.

Most Helpful This Week