Issues when using React useRef hook on Typescript Input tags

kypkk
3 min readMay 6, 2023

--

Photo by Lautaro Andreani on Unsplash

This is a problem that I encountered last night when coding react typescript. I was trying to use the useRef hook on an input tag but I keep doing it wrong. The solution that chatgpt gave me doesn’t work too. Hence, I am going to show how I successfully done it.

PS: I’m not sure whether my way is the best way or the correct way. So just comment if you know there is a better way

In the React js

Usually in reactjs we use useRef hook on input tags like this.

Get the input values from like this.

Finally reset the input like this.

React Typescript

First of all, the easy part just a little difference from the js version. Since the type of the html input tag is <HTMLInputElement>, you must declare the useRef like this.

After I declare the useRef, I try to get the value of the input element. I tried the js way but it gives me this error “inputRef.current’ is possibly ‘undefined.” and this is because the inputRef.current has multiple types <HTMLInputElement | undefined> . In this way, TypeScript has no guarantee that we’ll assign the ref to an element or assign a value to it, so its current property could possibly be null. So I used the optional chaining (?.) operator to check if the current property on the ref stores a null value.

Finally, same with the value, you cannot reset the input in a normal js way. I decided to use a if stement to check if the inputRef.current is undefined. If not then I may reset it.

Wrap up

The reason why I ran into this bug is that I was playing around with the OpenAI Dall-e Model and after I finish building the next.js api route I just stuck on building the front-end user Interface. Below is how the small side project look like. Thanks for reading, hope you guys enjoy this article.

Type in a prompt in the input and click generate and you’ll get a image that matches the prompt!

--

--

kypkk

我是一個想出國跟變強的資工系學生