Search code examples
reactjstypescriptreact-hooksuse-ref

Assigning ref to HTMLInputElement giving error in typescript


In useRef variable cannot set to input element

   const inputRef = React.useRef<HTMLInputElement>(null);

   <Input name="answer" ref={inputRef}/>

On the <Input ref=""> I'm Getting the following error

enter image description here

Any Idea How to Fix this. Thanks In Advance

My Full Code :

enter image description here


Solution

  • Your ref in not assigned to HTMLInputElement but an Input component. You need to define the type of it accordingly

    Since Input is a functional component, you can't specify a ref on it directly, you need to forward the ref and for that you need to use React.forwardRef

    const inputRef = React.useRef<HTMLInputElement>(null);
    ..
    <Input name="answer" ref={inputRef}/>
    
    ...
    const Input = React.forwardRef((props, ref: React.Ref<HTMLInputeElement>) => (
      <input ref={ref} {...props} />
    ));
    

    Since you are using semantic-ui-react, in order to pass on ref to the components, you need to make use of Ref component from the library

    import {Ref } from 'semantic-ui-react';
    ...
    
    const inputRef = React.useRef<HTMLInputElement>(null);
    ..
    <Ref innerRef={inputRef}><Input name="answer" ref={inputRef}/></Ref>
    

    Check a bit.dev for more details