Using React's "useRef" hook with Typescript

To use the useRef hook with Typescript, make sure to define a return type that matches your element type. In this example, the ref is to an HTMLInputElement.

function MyComponent() {
  const input = React.useRef<HTMLInputElement>(null)

  return (
    <form
      onSubmit={(e) => {
        e.preventDefault()
        alert('Value: ' + input.current.value)
      }}
    >
      <input ref={input} />
    </form>
  )
}

← Read all articles