Next.js Discord

Discord Forum

Focus an input onClick tsx type inconclusive?

Greenish Elaenia posted this in #help-forum
Open in Discord
Greenish ElaeniaOP This does exactly what I want to do but the code is jsx. What is the type of inputRef? If I do exactly as the provuded code does and say useRef(null), then later TS says there is no ".current" for null.

5 Replies

Greenish ElaeniaOP
Tried React.Ref but still shows ts error - "doesn't have .current"
maybe show your code?
const inputRef = useRef<HTMLInputElement | null>(null);

you will also see some materials with this simpler type
const inputRef = useRef<HTMLInputElement>(null);

which works too (most of the time), but this latter way won't work when you need to do something like
ref={el => {
  inputRef.current = el;
but if you just use ref={inputRef} directly, then both HTMLInputElement | null and HTMLInputElement work
basically the ref here is just an html element, so you give it the type of an html element. HTMLDivElement, HTMLInputElement, etc.