Before React 16.3 we were able to proxy the same element ref to multiple listeners, for example, to grab hold of the element for internal purposes and also expose it publicly, like so:
class MyComponent extends Component {
attachRef = el => {
this.buttonEl = el;
this.props.buttonRef(el);
}
// Do something with `this.buttonEl`
render () {
return <button ref={this.attachRef}>Button</button>;
}
}
After React 16.3 this is more complicated as the ref prop can be a function or an object:
class MyComponent extends Component {
buttonRef = React.createRef();
attachRef = el => {
this.buttonRef.current = el;
if (typeof this.props.inputRef === 'function') {
this.props.inputRef(el);
} else {
this.props.inputRef.current = el;
}
}
// Do something with `this.buttonRef.current`
render () {
return <button ref={this.attachRef}>Button</button>;
}
}
First, is this the right approach?
And if so, Typescript types say:
interface RefObject<T> {
readonly current: T | null;
}
Which prevents us from assigning to current. Shouldn't it not be readonly?
Before React 16.3 we were able to proxy the same element ref to multiple listeners, for example, to grab hold of the element for internal purposes and also expose it publicly, like so:
After React 16.3 this is more complicated as the ref prop can be a function or an object:
First, is this the right approach?
And if so, Typescript types say:
Which prevents us from assigning to
current. Shouldn't it not be readonly?