Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 (
        <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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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…

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); }} />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading