I'm trying to use a ref to an input element, and then use inputRef.current.value
to get its value
but I'm getting an error Object is possibly 'null'.ts(2531)
at inputRef.current
.
I tried several different solutions but I haven't got it to work yet. Any help is appreciated.
interface RefObject<T> {
readonly current: T | null
}
const Uncontrolled: React.FC = () => {
// const inputRef = useRef< HTMLInputElement | null> (null);
const inputRef:RefObject<HTMLInputElement> = useRef< HTMLInputElement | null> (null);
function alertValue() {
alert(inputRef.current.value); //Object is possibly 'null', under inputRef.current
}
return (
<div>
<p> Uncontrolled components do not have state data</p>
<input type="text" ref={inputRef} />
<button onClick={alertValue}>Click Me</button>
</div>
)
}
my solutions came from:
useRef TypeScript - not assignable to type LegacyRef<HTMLDivElement>