1const { forwardRef, useRef, useImperativeHandle } = React;
2
3// We need to wrap component in `forwardRef` in order to gain
4// access to the ref object that is assigned using the `ref` prop.
5// This ref is passed as the second parameter to the function component.
6const Child = forwardRef((props, ref) => {
7
8 // The component instance will be extended
9 // with whatever you return from the callback passed
10 // as the second argument
11 useImperativeHandle(ref, () => ({
12
13 getAlert() {
14 alert("getAlert from Child");
15 }
16
17 }));
18
19 return <h1>Hi</h1>;
20});
21
22const Parent = () => {
23 // In order to gain access to the child component instance,
24 // you need to assign it to a `ref`, so we call `useRef()` to get one
25 const childRef = useRef();
26
27 return (
28 <div>
29 <Child ref={childRef} />
30 <button onClick={() => childRef.current.getAlert()}>Click</button>
31 </div>
32 );
33};
34
35ReactDOM.render(
36 <Parent />,
37 document.getElementById('root')
38);
1constructor(props) {
2 super(props);
3 this.domElem = React.createRef();
4}
5
6getElem = () => {
7 return this.domElem;
8}
9
10render() {
11 return (
12 <div>
13 <div id="elem" ref={this.domElem}>Test Elem</div>
14 <Child getParentElem={this.getElem}/>
15 </div>
16 )
17}
18