(React) You cannot render a Router inside another Router

avatar
Borislav Hadzhiev

Last updated: Apr 7, 2024
2 min

banner

# (React) You cannot render a Router inside another Router

The error "You cannot render a <Router> inside another <Router>" occurs when we have 2 Router components in the same React application.

To solve the error, make sure to use a Router in your index.js file and not use any nested Router components.

you cannot render router inside another router

Make sure the App component in your index.js file is wrapped in a Router component.

index.js
import {createRoot} from 'react-dom/client'; import App from './App'; import {BrowserRouter as Router} from 'react-router-dom'; const rootElement = document.getElementById('root'); const root = createRoot(rootElement); // 👇️ Wrap the App component in a Router root.render( <Router> <App /> </Router> );
The code for this article is available on GitHub

And then remove any nested Router or BrowserRouter components from your App.

App.js
import React from 'react'; import {Route, Link, Routes} from 'react-router-dom'; // 👇️ don't wrap in <Router> export default function App() { return ( <div> <div> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> </ul> </nav> <Routes> <Route path="/about" element={<About />} /> <Route path="/" element={<Home />} /> </Routes> </div> </div> ); } function Home() { return <h2>Home</h2>; } function About() { return <h2>About</h2>; }

remove nested router or browser router components

The code for this article is available on GitHub

Your whole React application should only be wrapped in a single Router (or BrowserRouter) component.

The best place to wrap your React app with a Router component is in your index.js file because that's the entry point of your React application.

Once your entire app is wrapped with a Router component, you can use any of the hooks from the React router package anywhere in your components.

If you can't find where you are using the Router component, you can use your IDE to look for places where you are using <Router>.

In VSCode you can CTRL + Shift + f to search for <Router> and find nested instances of the Router (or BrowserRouter) component that you have to delete.

You should never have more than one Router in your React app.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.