Skip to content

Commit ee40c2a

Browse files
committed
refs-Call-child-method-from-parent
1 parent d91093e commit ee40c2a

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
First off, let me express that this is generally not the way to go about things in React land. Usually what you want to do is pass down functionality to children in props, and pass up notifications from children in events (or better yet: dispatch).
2+
3+
But if you must expose an imperative method on a child component, you can use refs. Remember this is an escape hatch and usually indicates a better design is available.
4+
5+
Using Hooks and Function Components
6+
7+
```js
8+
const { forwardRef, useRef, useImperativeHandle } = React
9+
10+
// We need to wrap component in `forwardRef` in order to gain
11+
// access to the ref object that is assigned using the `ref` prop.
12+
// This ref is passed as the second parameter to the function component.
13+
const Child = forwardRef((props, ref) => {
14+
// The component instance will be extended
15+
// with whatever you return from the callback passed
16+
// as the second argument
17+
useImperativeHandle(ref, () => ({
18+
getAlert() {
19+
alert("getAlert from Child")
20+
},
21+
}))
22+
23+
return <h1>Hi</h1>
24+
})
25+
26+
// useImperativeHandle customizes the instance value that is exposed to parent components when using ref.
27+
28+
const Parent = () => {
29+
// In order to gain access to the child component instance,
30+
// you need to assign it to a `ref`, so we call `useRef()` to get one
31+
const childRef = useRef()
32+
33+
return (
34+
<div>
35+
<Child ref={childRef} />
36+
<button onClick={() => childRef.current.getAlert()}>Click</button>
37+
</div>
38+
)
39+
}
40+
41+
ReactDOM.render(<Parent />, document.getElementById("root"))
42+
```

0 commit comments

Comments
 (0)