Search code examples
reactjsreact-routerreact-router-reduxreact-router-v4

NotFound route always showing with static routes - [React Router 4]


How can I define a notFound component with React Router 4 and static routes?

I use the nextversion of react-router-redux. So, in my client:

export default function appRoutes(history) {
  return (
    <ConnectedRouter history={history}>
      <div>
        {routes.map((route, key) => (
          <Route key={key} {...route} />
        ))}
      </div>
    </ConnectedRouter>
  );
}

And routes is:

export const routes = [
  {
    path: '/',
    component: App
  },
  {
    path: '/:lang/chat',
    component: Chat
  },
  {
    path: '/:lang',
    component: Listing
  },
  ...
  {
    path: '*',
    component: NotFound,
    status: 404
  },
];

With this approach, the component not found is always showing along with the matched route.

I have read that instead of wrapping the appRoutes method described above, with a div, I have to use Switch. But with this approach, the routes never match.

EDIT

I want to display, for example, App component and Listing component at the same time but the NotFound is also displaying.

So, what I'm doing wrong?


Solution

  • I found a solution that works for me. I have removed from static routes the App component and placed before and then I used Switch to render only one route.

    export default function appRoutes(history) {
      return (
        <ConnectedRouter history={history}>
          <div>
            <Route path='/' component={App} />
            <Switch>
              {routes.map((route, key) => (
                <Route key={key} {...route} />
              ))}
            </Switch>
          </div>
        </ConnectedRouter>
      );
    }