Skip to content

Instantly share code, notes, and snippets.

@treyhuffine
Last active April 9, 2020 09:01
Show Gist options
  • Save treyhuffine/d4c62f540a45d7d07231cb9cb81d7456 to your computer and use it in GitHub Desktop.
Save treyhuffine/d4c62f540a45d7d07231cb9cb81d7456 to your computer and use it in GitHub Desktop.
function FancyInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} ... />;
}
FancyInput = React.forwardRef(FancyInput);
// You can now get a ref directly to the DOM button:
const fancyInputRef = React.createRef();
<FancyInput ref={fancyInputRef}>Click me!</FancyInput>;
@polRk
Copy link

polRk commented Apr 9, 2020

function FancyInput(props, ref) {
It is not typescript code. Props and ref should not tot be any.

Use should use

const FancyInput: ForwardRefRenderFunction<HTMLInputElement, FancyInputProps>

And you will get type error

useImperativeHandle(ref, () => ({
    focus: () => {
      inputRef.current.focus();
    }
  }));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment