ric980
ric980

Reputation: 339

Router basename is not able to match the URL because it does not start with the basename

After upgrading to React Router v6, my application stopped working and I failed to find a way to achieve the same behavior with version 6.

This is the version I upgraded to: react-router-dom 6.2.1.

This is the code that worked with the previous version 5.2.0:

<Router basename="/#">
  <Route path="/login">
    <Login />
  </Route>
  <Route path="/">
    <Home />
  </Route>
</Router>

            
<Link to="/login">Login</Link>

And I navigate to http://localhost:3000/#/login. Now even http://localhost:3000 doesn't work.

This is the full error I get in the browser console:

<Router basename="/#"> is not able to match the URL "/" because it does not start with the basename, so the <Router> won't render anything.

I've read all I can find on StackOverflow, in the Github issues, the migration guide, tried a number of workarounds, but nothing seems to achieve the old behavior. It's like the v6 doesn't respect URL fragments at all.

I need the URL fragments so that when a user refreshes a page or bookmarks a URL, it actually works.

How to make this work with React Router v6?

Upvotes: 18

Views: 30620

Answers (2)

Vishwajeet Mishra
Vishwajeet Mishra

Reputation: 446

This is too sad that react documentation does not specify anything regarding basename in react router v6. however, I tried something and it worked. please find below solution. cheers!

<HashRouter> 
    <Routes>
        <Route path='/app'> {/* put url base here and nest children routes */}
            <Route path='path1' element={ <Somecomponent1 /> } />
            <Route path='path2' element={ <Somecomponent2 /> } />
        </Route>
        <Route path="/*" element={<Navigate to="/app/path1" />}  /> {/* navigate to default route if no url matched */}
    </Routes>
</HashRouter>

Upvotes: 16

jove0610
jove0610

Reputation: 854

You need wrap your Route component inside Routes component. Link to docs that explains this. There are also changes in Route component you need to look up.

Anyway, this should work:

<Router basename="/#">
  <Routes>
    <Route path="/login" element={<Login />} />
    <Route index path="/" element={<Home />} />
  <Routes>
</Router>
        

Upvotes: 6

Related Questions