How do I add 404 - Not Found page in React with React-Router?
Here's my attempt:
// routes.tsx
export const routes = [
{
path: '/students',
render: (props: any) => <List {...props} title={`Students`} />,
},
{
path: '/teachers',
render: (props: any) => <List {...props} title={`Teachers`} />,
},
]
// App.tsx
import { routes } from './routes'
function App() {
const routeComponents = routes.map(({ path, render }, key) => (
<Route exact path={path} render={render} key={key} />
))
return (
<ThemeProvider theme={theme}>
<CSSReset />
<Suspense fallback={<Loader />}>
<Router>
<Switch>
<Route exact path="/" component={Signin} />
<Route path="/signin" component={Signin} />
<Layout>{routeComponents}</Layout>
{/* <Route component={NotFound} /> */}
<Route path="*" component={NotFound} />
</Switch>
</Router>
</Suspense>
</ThemeProvider>
)
}
export default App
But I can't see my custom "404 - Not Found" page when I go to 'http://localhost:3000/nothing', but <Layout />
component.
What I am doing wrong?
Stack: TypeScript, [email protected], [email protected]
Layout
isn't a valid child ofSwitch
, onlyRoute
andRedirect
are. RemovingLayout
will allow switch to match the 404 route. reacttraining.com/react-router/web/api/Switch – Drew Reese<Layout />
in multiple pages ('/students'
,'/teachers'
) without adding in each one of them? – RarioSwitch
but still within theRouter
should work for you. Is there a reason you have it in the middle of the routes? – Drew Reese<Layout />
in several child components. But I guess I will just do that now. Thanks @DrewReese – Rario