Last active
December 4, 2020 12:09
-
-
Save createdbymahmood/30f4456d9314c4cfbe8ec0ac03898b20 to your computer and use it in GitHub Desktop.
Sample for useImperativeHandle
This file contains hidden or 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
const Register: FC = props => { | |
const formRef = useRef<ImperativeHandleProps>(null!); | |
return ( | |
<Fragment> | |
<Form ref={formRef} /> | |
<button onClick={() => formRef.current.onSomePropFired()}> | |
sbt form | |
</button> | |
</Fragment> | |
); | |
}; |
This file contains hidden or 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
type ImperativeHandleProps = HTMLFormElement & { | |
onSomePropFired: () => void; | |
}; | |
const Form = React.forwardRef< | |
ImperativeHandleProps, | |
HTMLProps<HTMLFormElement> | |
>((props, ref) => { | |
const formRef = useRef<ImperativeHandleProps>(null!) | |
const imperativeHandle = () => { | |
return { | |
onSomePropFired() { | |
console.log("onSomePropFired called"); | |
formRef.current.focus() | |
}, | |
} as ImperativeHandleProps; | |
}; | |
useImperativeHandle(ref, () => imperativeHandle()); | |
return <form ref={formRef} {...props}></form>; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment