Default Route With React Router 4

33,952

Solution 1

Actually, it's pretty straightforward...

Use Redirect component to... well, redirect.

<Redirect from="/steps" exact to="/steps/whatever" />

exact prop guarantees you won't be redirected from sub-route.

Edit: after all, Redirect does support exact (or strict) props. No need to wrap in Route. Answer updated to reflect that.

Solution 2

Pedr, I think that this will solve your problem.

<Route path="/" exact component={Home} />
<Route path="/select-steps" render={() => <StepSelectorContainer />} />
<Route path="/steps" component={StepsComponent} />

And then in your StepsComponent render method, you can do this.

<Switch>
{steps.map(step => (
    <Route
        path={fullPathForStep(step.uid)}
        key={shortid.generate()}
        render={() => <StepContainer step={step} />}
    />}
<Redirect from="/steps" exact to="/steps/alpha" />
</Switch>

What this will do is render your steps component because it the route begins with /steps. After that is rendered, then it will render one of the nested routes based off the url. If the url is just "/steps", then it will redirect to the initial route listed here, in this case "/steps/alpa" by rendering the redirect. The Switch will make it so that it only renders one of the routes.

Credit to Andreyco for the redirect code.

I hope this helps.

Share:
33,952
Undistraction
Author by

Undistraction

Updated on July 05, 2022

Comments

  • Undistraction
    Undistraction almost 2 years

    fI currently have the following routes defined in my application:

    /
    /selectSteps
    /steps
    /steps/alpha
    /steps/beta
    /steps/charlie
    

    Which could also be visualised like this:

    - (home)
        - selectSteps
        - steps
           - alpha
           - beta
           - charlie
    

    My root component looks like this:

      <Route path="/" exact component={Home} />
        <Route path="/select-steps" render={() => <StepSelectorContainer />} />
        <Route path="/steps" component={StepsContainer} />
    

    My Steps component does this:

    steps.map(step => (
      <Route
        path={fullPathForStep(step.uid)}
        key={shortid.generate()}
        render={() => <StepContainer step={step} />}
      />
    

    This all works nicely, but I don't want steps to exist as route in its own right. Only its child routes should be visitable. So I'm looking to lose the /steps route to leave my routes as:

    /
    /selectSteps
    /steps/alpha
    /steps/beta
    /steps/charlie
    

    How should I configure my routes for this? Ideally, hitting /steps would redirect to the first child route.