1import React, { useState } from “react”;
2import Child from “./Child”;
3function Parent(props) {
4const [text, setText] = useState(“Hello”);
5return (
6<div>
7<h1>{text}</h1>
8<Child changeText={(text) => setText(text)} />
9</div>
10);
11}
12export default Parent;
13
14
15
16import React from “react”;
17function Child(props) {
18return (
19<div>
20<button onClick={() => props.changeText(“World”)}>
21Change the text
22</button>
23</div>
24);
25}
26export default Child;
1In our case, it is easy to identify that the state should reside in the “Parent” component.
2
3const [text, setText] = useState(“Hello”);
4
5Now, what do we do to the “Parent” component? We pass the callback function as a prop from the parent component.
6
7<Child changeText={(text) => setText(text)} />
8
9Now we need a callback function in the “Child” component that is triggered when the button is clicked.
10
11<button onClick={() => props.changeText(“World”)}>
12
1class App extends React.Component {
2 constructor() {
3 super();
4 this.state = {value : ''}
5 }
6 handleChange = (e) =>{
7 this.setState({value: e.target.value});
8 }
9 render() {
10 return (
11 <div>
12 <input type="text" value={this.state.value} onChange={this.handleChange}/>
13 <div>{this.state.value}</div>
14 </div>
15 )
16 }
17}
18ReactDOM.render(<App/>, document.getElementById('app'));