Please wait...
ReactJs, we worked mostly in Components so today we're implementing component Parent and Child based and calling methods from each other.
For example here, When Calling Child method from Parent Component using a counter state in Child component and that will increase and reset counter state value from the parent Component
Calling Parent method from Child Component using a counter state in Parent Component and that same increase and reset counter state value from the Child Component
Parent.jsx
import React, {Component} from 'react';
import Child from "./Child";
export default class Parent extends Component {
constructor(props) {
super(props);
this.child = React.createRef();
}
onIncreaseCounterClick = () => {
this.child.current.increaseCounter();
};
onResetCounterClick = ()=>{
this.child.current.resetCounter()
}
render() {
return (
<div>
<button className="btn btn-primary" onClick={this.onIncreaseCounterClick}> Calling Child method</button>
<button className="btn btn-success" onClick={this.onResetCounterClick}> Reset Counter</button>
<Child ref={this.child}/>
</div>
);
}
}
As we can see above, we create a reference of Child Component that will help for access all methods of Child component in Parent Component.
ref={this.child}
Child.jsx
import React, {Component} from 'react';
export default class Child extends Component {
state = {
counter: 0
}
increaseCounter = () => {
this.setState({counter: this.state.counter + 1})
}
resetCounter = () => {
this.setState({counter: 0})
}
render() {
return (
<div>
<p>{this.state.counter} times clicked</p>
</div>
);
}
}
Output:
Parent.jsx
import React, {Component} from 'react';
import Child from "./Child";
export default class Parent extends Component {
state = {
counter: 0
}
increaseCounter = () => {
this.setState({counter: this.state.counter + 1})
}
resetCounter = () => {
this.setState({counter: 0})
}
render() {
return (
<div>
<Child resetCounter={this.resetCounter} increaseCounter={this.increaseCounter}/>
<p>{this.state.counter} times clicked</p>
</div>
);
}
}
Here we pass method as a props in Child Component so Child can use these methods from props and call onClick Button event
Child.jsx
import React, {Component} from 'react';
export default class Child extends Component {
render() {
return (
<div>
<button className="btn btn-primary" onClick={this.props.increaseCounter}> Calling Child method</button>
<button className="btn btn-success" onClick={this.props.resetCounter}> Reset Counter</button>
</div>
);
}
}
Output:
Previous Post arrow_back
How to implement WebSocket in Django using Channels and Stream WebSocket dataNext Post arrow_forward
Custom Django data migrations with RunPython Class