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?
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 !
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With