0

I'm trying to implement protected routes in React. Following is my implementation

if (isAuth()) {
      routesToRender = (
        <React.Fragment>
          {/* <Redirect exact from="/" to="/dashboard" /> */}
          <Route path="/" exact component={props => <Dashboard {...props} />} />
          <Route path="/dashboard" exact component={props => <Dashboard {...props} />} />
          <Route path="/settings/" exact component={props => <Settings {...props} />} />
        </React.Fragment>
      )
    } else {
      routesToRender = (
        <React.Fragment>
          <Route path="/signup/" exact component={props => <Signup {...props} />} />
          <Route path="/" exact component={props => <Login {...props} />} />
          <Redirect from="*" to="/" />
        </React.Fragment>
      )
    }

If not authenticated I want to redirect all the routes to root URL which is * and I use <Redirect from="*" to="/" /> for that. But I also want to be able to access /signup.

How do I redirect from all routes except one ?

Sooraj
  • 6,517
  • 4
  • 51
  • 87

1 Answers1

1

Instead of writing hardcoded routes for authentication, you should instead write an AuthRoute HOC,

const AuthRoute = ({component: Component, ...rest}) => {
    if(isAuth) {
        return <Route {...rest} component={Component} />
    }
    return <Redirect to="/" />
}

and use it like

<React.Fragment>
      {/* <Redirect exact from="/" to="/dashboard" /> */}
      <AuthRoute path="/" exact component={props => <Dashboard {...props} />} />
      <AuthRoute path="/dashboard" exact component={props => <Dashboard {...props} />} />
      <AuthRoute path="/settings/" exact component={props => <Settings {...props} />} />
 </React.Fragment>

Any Route that you do not want to Authenticate, will be written down as a normal Route

Shubham Khatri
  • 211,155
  • 45
  • 305
  • 318
  • But how do I redirect all the random routes to root? – Sooraj Oct 03 '18 at 06:50
  • Also in this case, even the normal routes are redirecting me to `/` – Sooraj Oct 03 '18 at 06:52
  • ``` isAuth() ? : } /> ``` This works for me. – Sooraj Oct 03 '18 at 06:59
  • @SoorajChandran, As I said, any normal Route which has to go through without the auth flow needs to be rendered as a `Route` and not `AuthRoute`. Also the random routes can simply be Redirect to `/` using `` But please note that, you should make use of Switch while rendering Routes – Shubham Khatri Oct 03 '18 at 07:05