ReactJS

Warning when using withRouter with new React Context API

React version : > 16.6

Getting this warning when using Context API with withRouter

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

This happens when use the React context API like this

Home.contextType = AppContext;
export default withRouter( Home ); // warning is triggering here

To fix this we need to use hoist-non-react-statics to automatically copy all non-React static methods. I used hoist-non-react-statics version 3.1.0.

Install `hoist-non-react-statics` using command `npm i hoist-non-react-statics` Link here

Import it in your file

import hoistNonReactStatics from 'hoist-non-react-statics';

After importing, export your component like this

Home.contextType = AppContext;
export default hoistNonReactStatics( Home, withRouter ( Home) );

Related reading here, here and here

Computer engineer interested in programming, electronics, application architecture, data visualization, automation and performance optimization.

Leave a Reply