4

I have 2 routes using same component (form), one to create new entry and the other to edit. State name has been removed from React Router, I can't just check if this.route.name === 'edit' => fetch(itemAPI).

One option is to write reducer/action to create "edit" state in my redux store, but I was wondering if it's the best practice and if there is an easier way to check where I am in the app (which route).

My routes:

<Route component={ItemNew} path='/items/edit/:id' />
<Route component={ItemNew} path='/items/new' />

In my ItemNew component, I'd like to:

componentDidMount () {
    let stateName = this.props.location.state
    if(stateName === 'edit') {
        this.props.fetchItem() // dispatch API action
    }
}

1 Answer 1

2

The Route component used to perform the final part of the match on the current URL shows up on this.props.route; the entire list of nested Routes that participated in the match is in the this.props.routes array. You can pass any arbitrary props onto these Routes and retrieve them later. For example:

<Route component={ItemNew} name="edit" path='/items/edit/:id' />
<Route component={ItemNew} name="add" path='/items/new' />

and

componentDidMount () {
  if(this.props.route.name === 'edit') {
    this.props.fetchItem() //dispatch API action
  }
}
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.