2

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>

Object is possibly null in TypeScript React

1 Answer 1

1

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

alert(inputRef.current!.value);

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

const [value, setValue] = useState('');
function alertValue() {
    alert(value);
}
// ...
<input value={value} onchange={e => { setValue(e.currentTarget.value); }} />
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, the ! worked, I'll look into optional chaining too. for this component I'm trying to make it uncontrolled on purpose hence the component name. I'll accept answer in 8 mins

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.