Reputation: 13703
I'm passing the ref using React.forwardRef
to the down component which usually works.
<SomeComponent
component={React.forwardRef((props, ref) => <MyComponent innerRef={ref} {...props} />)}
.../>
However when I have HOC (higher order component) withStyles, the innerRef along with other props do not get passed properly.
// innerRef does not exists in props
const MyComponent = withStyles(styles)(({ one, two, ...props }) => {
return (
<Fragment>
<NavLink {...props}></NavLink>
...
</Fragment>
);
})
Without using withStyles I get them perfectly
// innerRef exists in props
const MyComponent = ({ one, two, ...props }) => {
return (
<Fragment>
<NavLink {...props}></NavLink>
...
</Fragment>
);
}
How can I still have the withStyles HOC but with innerRef and other props included?
The issue appeared after migration from material ui v3 to v4. NavLink requires the innerRef property.
Upvotes: 2
Views: 1147
Reputation: 81086
withStyles
passes along innerRef as ref, so something like the following should work:
const MyComponent = withStyles(styles)(({ one, two, ...props }, ref) => {
return (
<Fragment>
<NavLink {...props} ref={ref}></NavLink>
...
</Fragment>
);
})
Or if you need to keep it as innerRef
on NavLink
:
const MyComponent = withStyles(styles)(({ one, two, ...props }, ref) => {
return (
<Fragment>
<NavLink {...props} innerRef={ref}></NavLink>
...
</Fragment>
);
})
Upvotes: 2
Reputation: 13912
My recommendation based on my comments:
<SomeComponent
component={React.forwardRef((props, ref) => <MyComponent nRef={ref} {...props} />)}
.../>
const MyComponent = withStyles(styles)(({ one, two, ...props }) => {
props.innerRef = nRef;
return (
<Fragment>
<NavLink {...props}></NavLink>
...
</Fragment>
);
})
Or alternatively
<NavLink {...props} innerRef={props.nRef}></NavLink>
Upvotes: 0