5

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?

1 Answer 1

3

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 !

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.