How to implement React route for following scenario?

Viewed 21

I have following routes. I have to implement a Application route in such a way that :

  1. It should redirect to /add-user page if user try to access invalid route. (Route which is not available.)
  2. User can able to access correct route directly from browser address bar.

I am looking for proper solution which will work for above scenario.

function AppRoutes({ setLoading }) {
    const routes = [
    {
        key: keys.ADD_USR,
        path: '/add-user',
        // eslint-disable-next-line react/display-name
        renderComponent: (crumbs) => <AddUserData crumbItem={crumbs} />,
        crumbs: [
            {
                selected: 'false',
                link: `${prefix}/add-user`,
                accessibilityText: 'Add user',
                linkTtile: 'Add user',
            },
        ],
    },
    {
        key: keys.VIEW_USR,
        path: '/view-user',
        // eslint-disable-next-line react/display-name
        renderComponent: (crumbs) => <UserDetails crumbItem={crumbs} />,
        crumbs: [
            {
                selected: 'false',
                link: `${prefix}/view-user`,
                accessibilityText: 'View user',
                linkTtile: 'View user',
            },
        ],
    },
    {
        key: keys.USER_GRID,
        path: '/user-grid',
        // eslint-disable-next-line react/display-name
        renderComponent: (crumbs) => <UserGrid crumbItem={crumbs} />,
        crumbs: [
            {
                selected: 'false',
                link: `${prefix}/user-grid`,
                accessibilityText: 'User grid',
                linkTtile: 'User grid',
            },
        ],
    },
]
    return (
        <div className="app-container">
            <Switch>
                {routes.map(({ key, path, crumbs, renderComponent }) => {
                    return (
                        <Route key={key} path={path}>
                            {renderComponent(crumbs)}
                        </Route>
                    )
                })}
                <Redirect to="/add-user" />
            </Switch>
        </div>
    )
}

1 Answers

remove Redirect component from the Switch.

Related