ThinkGeek
ThinkGeek

Reputation: 5117

Navigate to a different route programmatically

I have a usecase where I have a list of elements inside some component similar to vanilla html select. I want, when user clicks on any of the element inside list, route should change. Can I use some regex while defining route and change route by using some API method from react router, onValueChange event of select?

Example Root route: / List Data: Cat, Dog, Elephant

When someone clicks on Cat I want him to get navigated to /Cat, similarly /Dog, /Elephant.

Upvotes: 3

Views: 152

Answers (1)

John Ruddell
John Ruddell

Reputation: 25842

So after talking about it for a bit. figured out what you were wanting to do.

you need to define a new route in react-router that you can use for this history change.. something like this:

<Route exact path="/:name" component={SomeComponent} /> 

in your component you have access to this "name" via this.props.params.name

you can also call an action to update the store before updating this route


Note: if you stay with v2... You should make your actions return a promise, so that you can just chain the event in your component. aka:

onChange={this.handleChange}

handleChange = (value) => { // assuming you have the value here.. it may be e is the function param and you get the value as e.target.value
    this.props.saveSelectedAnimal(value).then( () => {
        this.props.history.push("/"); 
    })
}

Upvotes: 1

Related Questions