简体   繁体   中英

How to show 404 Error Page in React Router V6

I am using React for my webapp frontend. But during development, i came across routing problem in react-router-dom V6. That problem is i would like to show 404 error page if none of the routes is matched. Here is my code,

import React from 'react';
import { BrowserRouter,Routes,Route} from 'react-router-dom';
import Home from "./Pages/Home"
import Allposts from './Pages/Allposts'
import Createpost from './Pages/Createpost'
import Error404 from './Pages/Error404'

const App = () => {
    return(
        <>
        <BrowserRouter>
            <Routes>
                <Route path="/" element={<Home />}/>
                <Route path="/all-posts" element={<Allposts />}/>
                <Route path="/create-post" element={<Createpost />} />
                <Route path="*" element={<Error404 />} />
            </Routes>
        </BrowserRouter>
        </>
    )
}

export default App;

As you can see i have added catch all routes Route at the end with path equal to "*" mark. This catches all routes except the nested routes (and this is the problem ). By general rule, it should catch all routes whether that is nested or not nested and it should display that 404 error page component. When i am using route "localhost:3000/all-posts/12345" <--- as this route is not present it should display that 404 error page component instead of showing this it shows a just blank page and an error pops out in console saying resource not found with an error of 404 that's it.

This is the problem. How to solve this problem and show 404 error page component.

Hi did you try?

Try this

<Switch>
   <Route path='*' component={Error404} />
</Switch>

react can't check on it's own if the post exists or not, you can put a simple check like this to handle it

 if (post exists) { return <Post/>; //render Post info/details } else { return <Error404 />; // if not redirect to 404 }

If you could switch to this method, it would work for all the nested components as well.

import { createBrowserRouter, RouterProvider } from 'react-router-dom';

function Error404() {
  return <h2>404 Not found</h2>;
}

const router = createBrowserRouter([
  {
    path: '/',
    errorElement: <Error404 />,
    children: [
      {path: '', element: <Home /> },
      {path: 'all-posts', element: <Allposts /> },
      {path: 'create-post', element: <Createpost /> },
    ],
  },
]);

function Router() {
  return (
    <RouterProvider router={router} />
  );
}

export default Router;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM