How to call child method from parent in react

We usually pass the props to the child component from parent and pass notifications to parent by events. But sometimes we have some abnormal cases that we need to call the child method from the parent. In this, we could use Refs in React for solving.

For React with Hooks (v16.8+)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const ChildComponent = forwardRef((props, ref) => {
useImperativeHandle(ref, () => ({
sayHello() {
alert("Hello from Child");
}
}));

return <h1>Child Component</h1>;
});

const ParentComponent = () => {
const childRef = useRef();

return (
<div>
<ChildComponent ref={childRef} />
<button onClick={() => childRef.current.sayHello()}>Call child method</button>
</div>
);
};

For using Class Component

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class ChildComponent extends Component {
sayHello() {
alert('Hello from Child');
}

render() {
return <h1>Child Component</h1>;
}
}

class ParentComponent extends Component {
constructor(props) {
super(props);
this.childRef = React.createRef();
}

render() {
return (
<div>
<ChildComponent ref={this.childRef} />
<button onClick={() => this.childRef.current.sayHello()}>Click</button>
</div>
);
}
}

Comments

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×