With react-router-redux, how to programmatically redirect url

how can I programmatically redirect the url given the following packages:

"react-dom": "^15.5.4",
"react-redux": "^5.0.4",
"react-router-dom": "^4.1.1",
"react-router-redux": "^5.0.0-alpha.6",

      

It works for me:

import React from 'react';
import createBrowserHistory from 'history/createBrowserHistory';

class WorkPlacePage extends React.Component {
  render() {
    const history = createBrowserHistory();
    return (
      <div>
        <button onClick={() => history.push('/welcome/skills')}>next page</button>
      </div>
    );
  }
}

export default WorkPlacePage;

      

The problem with the above is that when the browser url changes, the response app doesn't seem to consider the url change as a redirect. A responsive app component that needs to run on a URL never runs the logic of the react components as if the url was hardcoded ...

How can I programmatically initiate a url redirect where the React app loads a new url?

Thank!

+3


source to share


1 answer


If you are using the new react API you need to use the history from this .props when inside components like this:

this.props.history.push('/some/path');

      

However, this can only be used to change the URL programmatically and not to navigate to the page. You should have some component mapping to this url inside your router config file as follows.



<BrowserRouter>
      <div>
        <Switch>
            <Route path="/some/path" component={SomeComponent} />
            <Route path="/" component={IndexComponent} />
        </Switch>
      </div>
</BrowserRouter>

      

Hope this helps. Happy coding!

+2


source







All Articles