Created
May 22, 2021 15:54
-
-
Save Sergioamjr/fb08f419356b3111c83925ea6a7f6b02 to your computer and use it in GitHub Desktop.
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 { useImperativeHandle, forwardRef, useEffect, useRef } from "react"; | |
const Input = forwardRef((props, parentRef) => { | |
const childRef = useRef(); | |
const someMethod = () => 1; | |
useImperativeHandle(parentRef, () => ({ | |
focusOnChildInput: () => childRef.current.focus(), | |
callChildMethod: someMethod, | |
})); | |
return <input ref={childRef} />; | |
}); | |
const Form = () => { | |
const ref = useRef(); | |
useEffect(() => { | |
if (ref) { | |
ref.current?.callChildMethod?.(); // 1 | |
ref.current?.focusOnChildInput?.(); | |
} | |
}, []); | |
return ( | |
<form> | |
<Input ref={ref} /> | |
</form> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment