-
Notifications
You must be signed in to change notification settings - Fork 7.8k
Closed
Description
Hello!
Let's say I'm creating a component that needs to manage its underlying DOM node, but also it needs to be able to forward the ref prop using the React.forwardRef() feature.
I believe that in this case I need to manually pass the node to the forwarded ref.
Here's some code for a better explanation:
class MyComponent extends React.Component {
constructor() {
super();
this.mount = this.mount.bind(this);
}
mount(n) {
// MyComponent needs to have access to the DOM node
this.el = n;
// But also it needs to forward the ref:
if (typeof this.props.forwardedRef === 'function') {
this.props.forwardedRef(n);
} else {
// But what do I do in case of a `React.createRef()` instance?
this.props.forwardRef.current = n; // is this okay?
}
}
render() {
return (
<input
type="text"
ref={
/* use both props.forwardedRef and this mount? */
this.mount
}
/>
);
}
}
export default React.forwardRef((props, ref) => (
<MyComponent {...props} forwardedRef={ref} />
));So as far as I understand it I need to manually assign the node to the current props of the React.createRef() object in case I'm dealing with it.
But i'm not sure if this will always be supported. It's not documented, at least.
Is it ok to do it like in the code above?
Also, I'm not sure if the this is an appropriate repo for this type of question. Should this issue be somewhere else or perhaps it'd be better on Stackoverflow?
Metadata
Metadata
Assignees
Labels
No labels