My react library obtains a ref by giving the client a callback ref function to put on the element that the library is to operate on:
Conceptually:
// --- library
export registerTarget = () => {
return (targetRef) => {
if (targetRef) {
targetRef.style = {color: "red"}; // or more funky library stuff.
}
}
}
// --- component
const targetMe = library.registerTarget('my-element');
return (
<div ref={targetMe}>This is my element for the library to operate on</div>
);
I've read that when you make the ref using createRef, then it's type is React.RefObject<T>
, but when you get the ref using a ref callback, you get the actual element.
The problem is that you are allowed to assign to ref.current.style
when ref
is a React.RefObject<T>
, but you are not allowed to assign to ref.style when ref is the thing that you got from a ref callback.
Or at least, I can't work out how to type the thing that I get from a ref-callback: I've tried HTMLElement
, but the error is that ref.style
is read-only in that case.