简体   繁体   中英

How to make "404 - Not Found" page/route with react-router?

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, React@v16.13.1, react-router-dom@v5.1.2

404 Page on react does not need to have a path as it needs to be a page rendered when roue is not found between the paths of the pages you already have. It should work this way:

      <Switch>
        <Route exact path="/" component={Signin} />
        <Route path="/signin" component={Signin} />
        {routeComponents()}
        <Route component={NotFound} />
      </Switch>

Left blank path="" . It will render 404 page.

see -

<Route path="" component={PageNotFound} />
<Route exact path="/" component={Signin} />
<Route path="/signin" component={Signin} />

This can fix

https://stackoverflow.com/a/64651959/16361679

return (
    <ThemeProvider theme={theme}>
      <CSSReset />
      <Suspense fallback={<Loader />}>
        <Router>
          <Switch>
            <Route exact path="/" component={Signin} />
            <Route path="/signin" component={Signin} />
            <Layout>
              <Switch>
                 {routeComponents}
                 <Route path="*" component={NotFound} />
              <Switch>
            </Layout>
            
          </Switch>
        </Router>
      </Suspense>
    </ThemeProvider>
  )

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