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?
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;
                        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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With