0

I don't think I'm fully understanding how to leverage react-router-redux. I understand that you can utilize:

<header>
    <Link to="/" className="nav-link">Home</Link>  
    <Link to="/about-us" className="nav-link">About Us</Link>
</header>

<main>  
    <Route exact path="/" component={Home} />
    <Route exact path="/about-us" component={AboutUs} />
</main>

By clicking on the links, the URL changes and different components are loaded. But how do I programmatically handle a change of component after a certain Action, for instance? I have an action that calls the server, manipulates the state, and then finally should re-route to a new Component. How does one handle this?

Ryan
  • 2,520
  • 3
  • 26
  • 39
  • I guess you possibly need to have a look at this https://stackoverflow.com/questions/44127739/programmatically-navigate-using-react-router/44128108#44128108 – Shubham Khatri Jan 21 '18 at 17:44

2 Answers2

1

import { Redirect } from 'react-router-dom'

after the action recieves response from server and dispatched the response, listen if response from server is available and return redirect within your render function

render () { 
  .... //render logic
if (responseFromServer) {
  <Redirect to='about-us' />
.... // rest of the render function and return statement
}

Update Based on your comment

I would do that in the about-us component.

const resetServerResponse = (serverResponse) => serverResponse = null // depends on typeof serverResponse could be empty string, bool or a set initial state.
......
dispatch(resetServerResponse)

so by the time you navigate back to the root / , responseFromServer is falsy andif (responseFromServer) {` will be skipped and not redirected.

Femi Oni
  • 682
  • 1
  • 7
  • 19
  • This works really well but what do you do to reset this variable after being redirected. If I navigate back to the original component, it automatically redirects me because the `responseFromServer` variable is still active in store. – Ryan Jan 22 '18 at 01:49
  • Thanks, this worked quite well but after some other searching, I actually preferred the following solution that allows for redirecting outside of the render method. https://stackoverflow.com/a/42320249/177941 – Ryan Jan 22 '18 at 23:50
0

If you are using react-router v4, you can import { push } from 'react-router-redux' and use it to dispatch any route like dispatch(push('/something')) in your actionCreator. No need to put that in your component logic.

See this example as well to get better clarity. ReactRouterAuth Example

Simranjit Singh
  • 564
  • 1
  • 4
  • 12