I have a component that uses a hook to set the input value into component state. I want to add a class when the input value is more than 0 characters in length, however I'm coming across an issue where TypeScript says my ref may be undefined.
I can't get rid of this error even if I check if the ref exists in the conditional that wraps the code to add the class. I'm not sure on the solution to this.
Error: Object is possibly 'undefined'
on inputValue.current.classList.add(inputHasContentClassName);
import React, { useState, useEffect, useRef } from 'react';
const Component: React.FC = () => {
const [inputValue, setInputValue] = useState('');
const myRef = useRef();
useEffect(() => {
const inputHasContentClassName = 'input--has-value';
if (inputValue.length > 0 && inputValue) {
inputValue.current.classList.add(inputHasContentClassName);
} else {
inputValue.current.classList.remove(inputHasContentClassName);
}
}, [inputValue]);
function handleInputChange(e: React.FormEvent<HTMLInputElement>) {
setInputValue(e.currentTarget.value);
}
function handleSubmit(e: React.FormEvent) {
e.preventDefault();
console.log('Submit form');
}
return (
<>
<section>
<form onSubmit={handleSubmit}>
<div>
<input
ref={myRef}
onChange={handleInputChange}
type="number"
/>
<label>Input Label</label>
</div>
<button
type="submit"
disabled={inputValue.length === 0}
>
Submit
</button>
</form>
</section>
</>
);
};
export default Component;