Skip to content

Instantly share code, notes, and snippets.

@Sergioamjr
Created May 22, 2021 15:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Sergioamjr/fb08f419356b3111c83925ea6a7f6b02 to your computer and use it in GitHub Desktop.
Save Sergioamjr/fb08f419356b3111c83925ea6a7f6b02 to your computer and use it in GitHub Desktop.
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