With React-Router-4, how to programmatically configure the `/`

advertisements

with React-Router-4 how can I programmatically set the index route /

For example, if the user is not authenticated, this should trigger:

<Route path="/" component={LandingPage}>

If the user is authenticated:

<PrivateRoute path="/dashboard" component={Dashboard} />

fyi on PrivateRoute

Thanks for suggestions/help!

UPDATED ATTEMPT

const WithMainLayout = ({component: Component, ...more}) => {
  return <Route {...more} render={props => {
    return (
      <MainLayout {...props}>
        <Component {...props} />
      </MainLayout>
    );
  }}/>;
};

const isLoggedIn = () => {
  console.log('do it')
  return true;
};

....

<WithMainLayout exact path="/" component={Home} render={() => (
  isLoggedIn() ? (
    <Redirect to="/dashboard" />
  ) : (
    <Home />
  )
)}/>

See above attempt, for some reason, the console.log is not outputting anything in the isLoggedIn func.


So in your Updated Code the problem is that you return

<Route {...more} render={props => {

so what essentially happens is that the render prop passed on to the WithMainLayout component which is available with {...more} is overwritten by you custom prop and hence isLoggedIn is never called.

The solution is simple, you can just interchange the {...more} and render={props => {}} and also wrap your Home component with WithMainLayout so that it doesn't miss the Layout

You code will look like

const WithMainLayout = ({component: Component, ...more}) => {
  return <Route render={props => {
    return (
      <MainLayout {...props}>
        <Component {...props} />
      </MainLayout>
    );
  }}  {...more} />;
};

const isLoggedIn = () => {
  console.log('do it')
  return true;
};

....

<WithMainLayout exact path="/" component={Home} render={() => (
  isLoggedIn() ? (
    <Redirect to="/dashboard" />
  ) : (
    <WithMainLayout component={Home} />
  )
)}/>