Shashika Virajh
Shashika Virajh

Reputation: 9487

How to manage routes in react

Im my react application, I want to manage my routes. I want to handle public and private routes properly. I did a bit of investigation but now im confused. There are ways, but I want to know how to handle it in the right way.

I found this component to handle private routes.

import React from 'react';
import { Redirect, Route } from 'react-router-dom';

const PrivateRoute = ({ component: Component, user, ...rest }: any) => (
  <Route
    {...rest}
    render={(props: Object) => (user ? <Component {...props} /> : <Redirect to='/login' />)}
  />
);

export default PrivateRoute;

Then it can be used as follows.

<Switch>
 <Route exact path='/login' render={() => setHomePage('login')} />
 <Route exact path='/register' render={() => setHomePage('register')} />
 <PrivateRoute user={auth.user} exact path='/dashboard' component={Dashboard} />
</Switch>

Or I can simply go like this.

let routes = (
      <Switch>
        <Route path="/auth" component={asyncAuth} />
        <Route path="/" exact component={BurgerBuilder} />
        <Redirect to="/" />
      </Switch>
    );

    if ( this.props.isAuthenticated ) {
      routes = (
        <Switch>
          <Route path="/checkout" component={asyncCheckout} />
          <Route path="/orders" component={asyncOrders} />
          <Route path="/logout" component={Logout} />
          <Route path="/auth" component={asyncAuth} />
          <Route path="/" exact component={BurgerBuilder} />
          <Redirect to="/" />
        </Switch>
      );
    }

    return (
      <div>
        <Layout>
          {routes}
        </Layout>
      </div>
    );

What will be the better way to handle this? Or is there any other elegant way?

Upvotes: 2

Views: 941

Answers (1)

The first one is better:

<Switch>
 <Route exact path='/login' render={() => setHomePage('login')} />
 <Route exact path='/register' render={() => setHomePage('register')} />

 <PrivateRoute user={auth.user} exact path='/dashboard' component={Dashboard} />
</Switch>

There'is <PrivateRoute/> components, this component will redirect the user to /login page is there's no user authenticated

The second one:

The second, all routes like checkout, orders will be indicated as not found, if user not authenticated

Upvotes: 2

Related Questions