Typescript React useRef object possibly null

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 (
            <p> Uncontrolled components do not have state data</p>
            <input type="text" ref={inputRef} />
            <button onClick={alertValue}>Click Me</button>

my solutions came from:

useRef TypeScript – not assignable to type LegacyRef<HTMLDivElement>

Object is possibly null in TypeScript React

>Solution :

While you could use optional chaining or ! to assert that the .current property isn’t nullish…


a better way would be to make the input controlled and log the state instead.

const [value, setValue] = useState('');
function alertValue() {
// ...
<input value={value} onchange={e => { setValue(e.currentTarget.value); }} />

Leave a Reply