Home > Mobile >  react router dom "no routes mached location" error / making components within router
react router dom "no routes mached location" error / making components within router

Time:10-12

I am making website which has admin and user pages.

In the beginning I combined both into a single <Routes>

<BrowserRouter>
  <Routes>
   // user related pages...
   <Route path="/" element={<>}/>
   <Route path="/signin" element={<>}/>
   .
   .
   .
  // admin related pages 
  <Route path="/admin" element={<>}/>
  <Route path="/admin/signin" element={<>}/>
  .
  .
  .
 </Routes>
</BrowserRouter>

And because the codes are getting longer in my Router.js, I decided to make components out of them => so User.js and Admin.js

like so:

<BrowerRouter>
  <User/>
  <Admin/>
</BrowserRouter>

in my User.js:

<Routes>
  <Route path="/" element={<>}/>
  <Route path="/signin" element={<>}/>
</Routes>

in my Admin.js:

<Routes>
  <Route path="/admin" element={<>}/>
  <Route path="/admin/signin" element={<>}/>
</Routes>

The problem: The router function works... But I get an warning in my console: ex.) No routes matched location ... (for each route I have set)

I googled why this happened, one person suggested using index for "/", but this didn't help...

Anyone who knows why this warning occurs?

CodePudding user response:

The issue it seems is that the Admin component isn't rendering a route for "/" since it is being rendered as the root route level. I suggest rendering both User and Admin on their own routes so the descendent routes they are rendering have correct paths and the overall path structure is maintained. Note that the root routes append a trailing "*" wildcard matcher to allow descendent route paths to also be matched.

Example:

<Routes>
  <Route path="/*" element={<User />} />
  <Route path="/admin/*" element={<Admin />} />
</Routes>

User

const User = () => (
  <Routes>
    <Route path="/" element={....} />
    <Route path="signin" element={....} />
  </Routes>
);

Admin

const Admin = () => (
  <Routes>
    <Route path="/" element={....} />
    <Route path="/signin" element={....} />
  </Routes>
);

Edit react-router-dom-no-routes-mached-location-error

CodePudding user response:

In your index.js pls try it. Hope it would work.

import { BrowserRouter } from 'react-router-dom';
 <BrowserRouter>
      <App />
 </BrowserRouter>

And in App.js.

import {Routes,Route} from "react-router-dom";
 <Routes>
        <Route path="/" element={<Home/>} />
        <Route path="/user" element={<User/>} />
        <Route path="/admin" element={<Admin />} />
 </Routes>
  • Related