I just upgraded to v6beta for react-router-dom because I wanted to organize my routes, but the 404 page is now broken:
export function AllRoutes(props) {
return(
<Routes>
<Route path="/about-us">
<Route path="contact"> <AboutContact/> </Route>
<Route path="our-logo"> <AboutLogo/> </Route>
<Route path="the-mission"> <AboutMission/> </Route>
<Route path="the-team"> <AboutTeam/> </Route>
<Route path="our-work"> <AboutWork/> </Route>
</Route>
<Route path="/user">
<Route path="sign-in"> <UserSignIn/> </Route>
<Route path="sign-up"> <UserSignUp/> </Route>
</Route>
<Route path="/">
<Home/>
</Route>
<Route >
<NotFound/>
</Route>
</Routes>
)
}
So everything works as expected (including the home page) except the not found page, which does not work even when adding path="/*"
or path="*"
Any easy solution for this?
<Routes>
// Use it in this way, and it should work:
<Route path='*' element={<NotFound />} />
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/settings" element={<Settings />} />
</Routes>
React Router v6 does not use exact attribute to match the exact routes. By default it matches the exact route. To match any value use "*" in the route path.
<BrowserRouter>
<div className="App">
<Header />
</div>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/profile" element={<Profile />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter> enter code here
react router v6 don't have Switch so you need to declare path='*'
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact/>} />
<Route path="*" element={<NotFound/>} />
</Routes>
</BrowserRouter>
Just you have to do is render a Route with a path of *, and React Router will make sure to only render the element if none of the other Routes match. (if your 404 component name is PageNotFound>
<Route path="*" element={<PageNotFound/>} />
1 Stackblitz link (its implementation is a little bit different)
try this is code:
export function AllRoutes(props) {
return(
<Routes>
<Switch>
<Route exact path="/">
<Home/>
</Route>
<Route path="/about-us">
<Route path="contact"> <AboutContact/> </Route>
<Route path="our-logo"> <AboutLogo/> </Route>
<Route path="the-mission"> <AboutMission/> </Route>
<Route path="the-team"> <AboutTeam/> </Route>
<Route path="our-work"> <AboutWork/> </Route>
</Route>
<Route path="/user">
<Route path="sign-in"> <UserSignIn/> </Route>
<Route path="sign-up"> <UserSignUp/> </Route>
</Route>
<Route path="*">
<NotFound/>
</Route>
</Switch>
</Routes>
)
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.