Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use hoist-non-react-statics with withRouter

How to use hoist-non-react-statics with withRouter

I am adding a static method in Feedback component.

This was my original code. I am trying to use new changes in Context API (react v 16.6)

Feedback.contextType = AppContext;

export default withRouter( Feedback );

This works fine, but I am getting the below warning in console.

Warning: withRouter(Feedback): Function components do not support contextType.

So to fix the warning I used the method proposed by Dan here. Its also mentioned in react docs

So I have this code now which is not working.

Imported the hoist-non-react-statics

import {Link, withRouter} from 'react-router-dom';
import hoistNonReactStatics from 'hoist-non-react-statics';

And exported the component like this

Feedback.contextType = AppContext;
hoistNonReactStatics( Feedback, withRouter(Feedback) );

export default Feedback;

but for some reason router info (history, match etc) is not populated in props

Any pointers why its not working?

like image 331
phantomCoder Avatar asked Nov 10 '18 14:11

phantomCoder


2 Answers

The second snippet isn't supposed to work because withRouter(Feedback) isn't exported from the module.

As linked issue explains, the problem was that hoist-non-react-statics wasn't treated contextType static property correctly. This has been fixed in latest hoist-non-react-statics version. Since react-router uses older hoist-non-react-statics version as a dependency, this could be fixed in-place:

Feedback.contextType = AppContext;

export default Object.assign(withRouter(Feedback), { contextType: undefined });

Or:

Feedback.contextType = AppContext;

const FeedbackWithRouter = withRouter(Feedback);
delete FeedbackWithRouter.contextType;
export default FeedbackWithRouter;

Or:

export default withRouter(Feedback);

Feedback.contextType = AppContext;
like image 101
Estus Flask Avatar answered Nov 05 '22 16:11

Estus Flask


I had that warning with and without 'hoist-non-react-statics' using, and it has disappeared when I had updated react-router-dom to the latest version (5.0.0)

like image 2
Elena Dontsova Avatar answered Nov 05 '22 17:11

Elena Dontsova