1

I am trying to render a Not Found page if no routes are found. I have the routes separated as modules. So when I do the switch statement adding the not found page at the bottom of the switch, such as:

const AccessRoutes = () => {
return (
    <React.Fragment>
        <Route path="/login" exact component={Login}/>
        <Route path="/register" exact component={Register} />
        <Route path="/forgot-password" exact component={ForgotPassword}/>
    </React.Fragment>
       )
}
export default () => {
    return (
     <Switch>
         <AccessRoutes/>
         <Route render={() => <div>Not found</div>}
     </Switch>
    )
}

The not found path never gets matched when you enter a path that is not on AccessRoutes, for example /hey shows a blank screen. If I put the routes without wrapping them in another component it works.

What am I missing?

Albert Alises
  • 1,018
  • 1
  • 8
  • 19
  • I think `Switch` only cares about immediate children that are `Route` components, so putting them in a separate component will not work. – Tholle Nov 23 '18 at 12:06
  • Yes, it is related to https://github.com/ReactTraining/react-router/issues/5785. The problem is using the fragment so it is not an immediate child... – Albert Alises Nov 23 '18 at 12:07
  • @YorkeUtopy Probably this solution will help you generically to handle 404 Routes, https://stackoverflow.com/questions/42929472/react-router-v4-default-pagenot-found-page/52261444#52261444 Also its better to redesign your app so that the Routes are enclosed by Switch where it has to be instead of rendering another component within switch followed by other Routes – Shubham Khatri Nov 23 '18 at 12:50

1 Answers1

5

Maybe this one helps you:

export const routes = [
    {
        path: '/login',
        exact: true,
        component: Login
    }, {
        path: '/register',
        exact: true,
        component: Register
    }, {
        path: '/forgot-password',
        exact: true,
        component: ForgotPassword
    }, {
        path: '*',
        component: () => <div>Not found</div>
    }
];

export default () => {
    return (
        <Switch>
            {
                routes.map(
                    (route, index) => <Route key={index} {...route}/>
                )
            }
        </Switch>
    )
}
Sagar Jajoriya
  • 2,377
  • 1
  • 9
  • 17
  • This actually works fine for my purposes! Not putting it on a component but a function that maps the routes. Although I find a component approach to be more elegant... – Albert Alises Nov 23 '18 at 13:31