withSyles HOC does not pass innerRef along with other props when passing through React.forwardRef

1k Views Asked by At

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.

2

There are 2 best solutions below

6
Ryan Cogswell On BEST ANSWER

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>
    );
})
0
TKoL On

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>