How can I use a React ref as a mutable instance, with Typescript? The current property appears to be typed as read-only.
I am using React + Typescript to develop a library that interacts with input fields that are NOT rendered by React. I want to capture a reference to the HTML element and then bind React events to it.
const inputRef = useRef<HTMLInputElement>();
const { elementId, handler } = props;
// Bind change handler on mount/ unmount
useEffect(() => {
inputRef.current = document.getElementById(elementId);
if (inputRef.current === null) {
throw new Exception(`Input with ID attribute ${elementId} not found`);
}
handler(inputRef.current.value);
const callback = debounce((e) => {
eventHandler(e, handler);
}, 200);
inputRef.current.addEventListener('keypress', callback, true);
return () => {
inputRef.current.removeEventListener('keypress', callback, true);
};
});
It generates compiler errors: semantic error TS2540: Cannot assign to 'current' because it is a read-only property.
I also tried const inputRef = useRef<{ current: HTMLInputElement }>();
This lead to this compiler error:
Type 'HTMLElement | null' is not assignable to type '{ current: HTMLInputElement; } | undefined'.
Type 'null' is not assignable to type '{ current: HTMLInputElement; } | undefined'.
HTMLInputElement
is correct, but inputRef should be set tonull
initially,useRef<HTMLInputElement(null)
– Lunn<input ref={myRef} />
- not settingmyRef.current = ...
– Arrearageref7
– Lunn