0

I have been trying to understand nested routes and switch in the React v4 Router. Consider the main router looks like this (simplified):

<Switch>
  <Route path="/" component={LoginPage} exact={true} />
  <Route path="/dashboard/edit/:id" component={DashboardPage} />
  <Route path="/dashboard" component={DashboardPage} />
</Switch>

The "dashboard" component renders the sub-route:

  render(){
    return (
      <div className="note">
        <Route to='/edit/:id' render={(props) =>
          <div>
            <NoteList {...props} />
            <EditNotePage {...props} />
          </div>
        } />
      </div>
    )
  }

The "EditNotePage" component can access the param by:

const mapStateToProps = (state, props) => ({
  note: state.notes.find((note) => note.id === props.match.params.id
});

Is this the correct approach? It seems a little redundant to specify "/dashboard/edit/:id" twice ( ? ) Once in main router and the again in the dashboard component.

However, if I do not match the route in the main router "Switch" the "props.match.params.id" is not accessible since "props.match" will only point to "/dashboard" .

Have I missed something crucial regarding how the React v4 Router works? :)

Kind regards Kermit

chazsolo
  • 7,873
  • 1
  • 20
  • 44
Kermit
  • 2,865
  • 3
  • 30
  • 53

1 Answers1

2

Nope, didn't miss anything. That's how react router v4 works. You define full routes. The trick you can use is that you can grab the current path and prepend it to your "nested path".

ZekeDroid
  • 7,089
  • 5
  • 33
  • 59
  • Ok, fantastic! Can you give me a simple example of how to grab the current path and prepend it? path={`${match.url}/edit/:id`} ? – Kermit Nov 20 '18 at 18:24
  • I would use `location`: `this.props.location.pathname`. Use that instead of `match.url` and it should work like you expect! – ZekeDroid Nov 20 '18 at 19:07
  • Alternatively, for larger projects and for maintainability purposes, I would use a constants file and export these "base paths". Then import them everywhere you need them. This will help you track down bugs with routing further down, if you'd like. – ZekeDroid Nov 20 '18 at 19:08