How to fix the ‘You should not use Link outside a Router’ error with React Router?

Sometimes, we want to fix the ‘You should not use Link outside a Router’ error with React Router.

In this article, we’ll look at how to fix the ‘You should not use Link outside a Router’ error with React Router.

How to fix the ‘You should not use Link outside a Router’ error with React Router?

To fix the ‘You should not use Link outside a Router’ error with React Router, we should make sure Link is only used in components that are inside Router.

For instance, we write

const App = () => (
  <BrowserRouter>
    <div className="sans-serif">
      <Route path="/" component={Main} />
      <Route path="/view/:postId" component={Single} />
    </div>
  </BrowserRouter>
);

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

to add some Routes in BrowserRouter.

Then we Link in Main by writing

import React from "react";
import { Link } from "react-router-dom";

const Main = () => (
  <div>
    <h1>
      <Link to="/">Example</Link>
    </h1>
  </div>
);

export default Main;

Conclusion

To fix the ‘You should not use Link outside a Router’ error with React Router, we should make sure Link is only used in components that are inside Router.