(React) You cannot render a Router inside another Router


Borislav Hadzhiev

Fri Apr 29 20222 min read

(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.

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 App in Router root.render( <Router> <App /> </Router> );

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

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>; }

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.

Use the search field on my Home Page to filter through my more than 1,000 articles.