Skip to content Skip to sidebar Skip to footer

React Router With Conditions

My react component looks like this: class App extends React.Component { render() { debugger; if(!this.props.isUserExist) { return (

Solution 1:

In a simpler way for individual paths, you can go with,

<Route exact path="/" component={()=>this.props.isUserExist?<HomePage/> : <Dashboard/>} />

Solution 2:

In short, React Router isn't built with a custom solution for this scenario. It's lightweight enough to let the developer decide what would be the better option.

Long story, it depends. If you expect the code to have to have common routes, which it doesn't in this example, it might be more maintainable to use inline Javascript and operator (&&). For example:

classAppextendsReact.Component {  
  render() {
    return (
      <div><Switch>
          {this.props.isUserExist && 
          <Routeexactpath="/"component={HomePage} /><Routeexactpath="/list"component={ListPage} />
          }
          <Routeexactpath="/dashboard"component={DashboardPage} /><Routecomponent={NotFoundPage} /></Switch></div>
    );
  }
}

In the scope of this example, (Dashboard only accessible to logged out users, not found page is only accessible to logged in users) your example is demonstrating the concept early return, which is a good pattern. It's a way to avoid writing else and to signal what the main code path is (user authenticated) and what the occasional code path is (user isn't authenticated). Read more about the early return here.

There are also other ideas around this, such as building your own custom PrivateRoute. An example of this idea is demonstrated here.

Post a Comment for "React Router With Conditions"