React router dom v5 default route doesn't work

Viewed 1327

I'm using react router dom v5 with material ui, and I have my routes in the following way:

import React from 'react'
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import Layout from '../components/layout'
import Login from '../screens/Login'
import NotFound from '../screens/NotFound'
import routes from './routes'

const DynamicRoutes = () => {
  return (
    <>
      {Object.values(routes).map(({ component, path }) => (
        <Route exact path={path} key={path} component={component} />
      ))}
    </>
  )
}

const Router = () => {
  return (
    <BrowserRouter>
      <Switch>
        <Route exact path="/login" component={Login} />
        <Layout>
          <DynamicRoutes />
        </Layout>
        <Route path="*" component={NotFound} />
      </Switch>
    </BrowserRouter>
  )
}

export default Router

I have already tried with <Route component={NotFound} />, and neither worked to me. Can anyone help me? The rest of routes work correctly, but when I type a fake route, doesn't go to the NotFound screen.

1 Answers

That occurs because all children of a <Switch> should be <Route> or <Redirect> elements. You can check more about it in react-router-dom docs.

So, one solution for your code would be do something like that:

<BrowserRouter>
      <Switch>
        <Route exact path="/login" component={Login} />
        {Object.values(routes).map(({ Component, path }) => (
          <Route exact path={path} key={path}>
            <Layout>
              <Component />
            </Layout>
          </Route>
        ))}
        <Route path="*" component={NotFound} />
      </Switch>
</BrowserRouter>

*For your routes object array, Component property must be with an upper C.

You can check this sample code.

Related