Focus an input onClick tsx type inconclusive?
Unanswered
Greenish Elaenia posted this in #help-forum
Greenish ElaeniaOP
https://react.dev/learn/manipulating-the-dom-with-refs#example-focusing-a-text-input 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"
Munchkin
maybe show your code?
@Greenish Elaenia https://react.dev/learn/manipulating-the-dom-with-refs#example-focusing-a-text-input 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.
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
workbasically the
ref
here is just an html element, so you give it the type of an html element. HTMLDivElement
, HTMLInputElement
, etc.