Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With react-router-redux, how to programmatically redirect to a URL

How can I programmatically redirect to a 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",

I have this working:

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 while the browser's URL changes, the React app doesn't seem to be treating the URL change as a redirect. The React app component that should be triggered by the URL is never running the React component logic in the way it would if the URL was hard refreshed.

How can I programmatically trigger a URL redirect where the React app loads the new URL?

like image 786
AnApprentice Avatar asked Oct 18 '22 11:10

AnApprentice


1 Answers

If using the newer react-router API, you need to make use of the history from this.props when inside of components so:

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

However this may be only used to change the URL programatically, not to actually navigate to the page. You should have some mapping of component to this URL inside your router config file like this.

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

Hope this helps. Happy Coding !

like image 161
Ravindra Ranwala Avatar answered Oct 21 '22 05:10

Ravindra Ranwala