Created
April 20, 2019 18:42
-
-
Save iMega/72d88132165490ce3c83bb3a925ce220 to your computer and use it in GitHub Desktop.
Using Hooks and Function Components (>= [email protected])
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { forwardRef, useRef, useImperativeHandle } from 'react'; | |
// We need to wrap component in `forwardRef` in order to gain | |
// access to the ref object that is assigned using the `ref` prop. | |
// This ref is passed as the second parameter to the function component. | |
const Child = forwardRef((props, ref) => { | |
// The component instance will be extended | |
// with whatever you return from the callback passed | |
// as the second argument | |
useImperativeHandle(ref, () => ({ | |
getAlert() { | |
alert("getAlert from Child"); | |
} | |
})); | |
return <h1>Hi</h1>; | |
}); | |
const Parent = () => { | |
// In order to gain access to the child component instance, | |
// you need to assign it to a `ref`, so we call `useRef()` to get one | |
const childRef = useRef(); | |
return ( | |
<div> | |
<Child ref={childRef} /> | |
<button onClick={() => childRef.current.getAlert()}>Click</button> | |
</div> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment