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
CodePudding user response:
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); }} />