zsayn zsayn - 21 days ago 5
Javascript Question

React-router browserHistory.push doesn't redirect

Trying to use

browserHistory.push
method to change my route programmatically.

It will change the route (per browser address bar) but doesn't update the view.

Here's my code
App.jsx

const AppStart = React.createClass({

render: function() {
return (
<MuiThemeProvider>
<Router history={hashHistory}>
<Route path="/" component={Main}>
<Route path="experiences" component={Experiences} />
<Route path="people" component={Profiles} />
<Route path="login" component={Login} />
<IndexRoute component={Home}/>
</Route>
</Router>
</MuiThemeProvider>
);
}
});

ReactDOM.render(
<AppStart />,
document.getElementById('app')
);


Component:

handleLoginRedirect(e) {
browserHistory.push('/experiences');
},

render() {
return (
<div className='row'>
<div className='col-sm-10 col-sm-offset-1'>
<form role='form'>
<RaisedButton label="Redirect" onClick={this.handleLoginRedirect} />
</form>
</div>
</div>
);

Answer

Your router configuration code is using 'hashHistory' while you are pushing to a 'browserHistory'. It's easy to miss something like this and it's understandable.

Just change your router code to use 'browserHistory' and it should start working. Like below:

const AppStart = React.createClass({

  render: function() {
    return (
      <MuiThemeProvider>
        <Router history={browserHistory}>
          <Route path="/" component={Main}>
            <Route path="experiences" component={Experiences} />
            <Route path="people" component={Profiles} />
            <Route path="login" component={Login} />
            <IndexRoute component={Home}/>
          </Route>
        </Router>
      </MuiThemeProvider>
    );
  }
});