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
Using this keyword access component properties and methods
How to create simple React Router to navigate multiple pages?
Integrate Bootstrap with ReactJS Application
How to use function inside JSX expression?
How to perform computation inside expression using ternary operator?
How to use onChange and onClick event in React JS?
Getting Started with React and Hello World Example
3 Different Examples - How State Works in React?
Component displays Height and Width on window resize
How to show hide component on Click in React JS?