Simple Conditional Routing in Reactjs

To help answer your question, I think you may need to also ask how that route should get blocked. Looking through the example above, you don’t yet have a mechanism that helps answer the question of “should I be able to visit this page”. That might come from state, redux, or some other means of determining if the user is logged in.

Since react-router is just plain React (one of my favorite parts!!) you have all the tools available to you that you would to conditionally show any part of your React app.

Here are a couple examples of how you might achieve this (by no means is this exhaustive. Be creative! It all depends on your requirements and the tools you are using)

class AllRoutes extends Component{
  render(){
    return(
      <Switch> 
        <Route exact path="/login" component={Login} />
        <Route exact path="/signup" component={SignUp} />
        { this.state.authenticated && 
          <Route exact path="/Welcome" component={Welcome} />
        }
      </Switch>
    );
  }
}

One of my favorite ways to accomplish this is creating a ProtectedRoute component

class ProtectedRoute extends Component {
  render() {
    const { component: Component, ...props } = this.props

    return (
      <Route 
        {...props} 
        render={props => (
          this.state.authenticated ?
            <Component {...props} /> :
            <Redirect to='/login' />
        )} 
      />
    )
  }
}

class AllRoutes extends Component {
  render() {
    return (
      <Switch>
        <Route path="/login" component={Login} />
        <ProtectedRoute path="/welcome" component={Welcome} />
      </Switch>
    )
  }
}

While I didn’t include any specific logic to how state.authenticated was set, this may come from anywhere (by no means does it needs to come from state). Do your best to answer the question of “how do I determine whether a user is authenticated” and use that mechanism as the means to handle route authentication.

Leave a Comment