How to fix the ‘You should not use Route or withRouter() outside a Router’ error with React Router v4?

Sometimes, we want to fix the ‘You should not use Route or withRouter() outside a Router’ error with React Router v4.

In this article, we’ll look at how to fix the ‘You should not use Route or withRouter() outside a Router’ error with React Router v4.

How to fix the ‘You should not use Route or withRouter() outside a Router’ error with React Router v4?

To fix the ‘You should not use Route or withRouter() outside a Router’ error with React Router v4, we should wrap our app with the BrowserRouter component.

For instance, we write

import { BrowserRouter } from "react-router-dom";

ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById("root")
);

to call ReactDOM.render with BrowserRouter wrapped around App so that we can use withRouter and Route in any component wrapped inside it without errors.

Conclusion

To fix the ‘You should not use Route or withRouter() outside a Router’ error with React Router v4, we should wrap our app with the BrowserRouter component.