How to show 404 Error Page in React Router V6

Viewed 1361

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 .

0 Answers
Related