How to redirect to /user/dashboard

Viewed 114

I have to redirect to the /user/dashboard page after login, but every time I close the tab and open it again it is opening the default home page i.e /.

import React from 'react';
import {isAuthenticated} from '../helpers/auth' 
import {Route, Redirect } from 'react-router-dom';
const UserRoute = ({component: Component, ...rest}) => {
    return(
        <Route 
            {...rest}
            render={(props)=>
                isAuthenticated() && isAuthenticated().role === 0 ? (
                    <Component {...props} />
                ):(
                    <Redirect to="/signin" />
                )
            }
        />
    );
}

export default UserRoute;

1 Answers

Here is a general example of route setup which does check for "Public", "Private" and index paths:

export default function Routes() {

  function fromIndex() {
    if (isAuthenticated) { // use your authentication mechanism
        return '/user/dashboard'
    }
    return '/login'
  }

  return (
    <Router history={history}> {/* history not required when using BrowserRouter */}
      <Switch>
        <Redirect exact from="/" to={fromIndex()} />

        {/* publicPaths is an array of paths: [{...} */}
        {publicPaths.map(item => (
          <PublicRoute exact={item.exact} key={item.path} path={item.path}>
            <item.component />
          </PublicRoute>
        ))}

        {privatePaths.map(item => (
          <PrivateRoute exact={item.exact} key={item.path} path={item.path}>
            <item.component />
          </PrivateRoute>
        ))}

        <NotFoundPage />
      </Switch>
    </Router>
  )
}

Here, PrivateRoute is a component which renders the children if authenticated otherwise redirects back to '/login'.

And PublicRoute is a component which renders the children if not authenticated otherwise redirects back to "/".

Related