Last active
April 23, 2020 23:43
-
-
Save cassidoo/6aa3cd63212682cc4279fd467a92bfb3 to your computer and use it in GitHub Desktop.
forwardRef example
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
export const SomeButton = forwardRef( | |
( | |
{ children, onSelect, ...props }, | |
forwardedRef | |
) => { | |
return ( | |
<button | |
{...props} | |
onClick={onSelect} | |
ref={forwardedRef} | |
> | |
{children} | |
</button> | |
) | |
} | |
) | |
// And then the user of the component can useRef to make a ref that it can interact with | |
function SomeButtonUser() { | |
let buttonRef = useRef() | |
useLayoutEffect(() => { | |
const { current } = buttonRef | |
// do stuff with the ref | |
}, []) | |
return ( | |
<div> | |
I have a button here: | |
<SomeButton ref={buttonRef} onClick={() => { console.log("I was clicked!") }}>poop</SomeButton> | |
</div>) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment