Last updated: Apr 7, 2024
Reading time·2 min
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.
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 the App component in a Router root.render( <Router> <App /> </Router> );
And then 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.
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.
You can learn more about the related topics by checking out the following tutorials: