I've followed the documentation and this blog post but I'm struggling to get anything to work.
Locally, I get the following error: HEY, LISTEN! No valid DOM ref found. If you're converting an existing component via posed(Component), you must ensure you're passing the ref to the host DOM node via the React.forwardRef function.
So I've attempted to forward the ref:
class ColorCheckbox extends Component {
setRef = ref => (this.ref = ref);
constructor(props) {
super(props);
}
render() {
const { key, children, color } = this.props;
return (
<button
ref={this.setRef}
key={key}
style={{
...style.box,
background: color,
}}
>
{children}
</button>
);
}
}
export default forwardRef((props, innerRef) => (
<ColorCheckbox ref={innerRef} {...props} />
));
Which is working as I'm able to console.log
the ref
inside my parent Component:
ColorCheckbox {props: Object, context: Object, refs: Object, updater: Object, setRef: function ()…}
"ref"
However, I still receive the message (above) of No valid DOM ref found...
.
Here's a simple Codesandbox describing my issue.
About the Codesandbox:
I am getting cross-origin errors in this Sandbox (they do not occur locally). If you change line 14 to be ColorCheckbox
the cross-origin error goes...
Any ideas?
When you call forwardRef on a class based component and try to pass the ref through the ref attribute it will not work. The documentation example will only work for regular DOM elements. Rather try doing the following:
export default forwardRef((props, innerRef) => (
<ColorCheckbox forwardRef={innerRef} {...props} />
));
I've just used an arbitrary name, so in this case forwardRef, to pass the ref as a prop. In your class based component I've changed the part where the ref is set on the button to this:
const { key, children, selected, color, forwardRef } = this.props;
return (
<button
ref={forwardRef}
key={key}
style={{
...
The following approach, which they feature in their blog post, will only work for regular DOM elements and styled-components:
const MyComponent = forwardRef((props, ref) => (
<div ref={ref} {...props} />
));
Please refer to my Codesandbox fork to see a working example.