Reputation:
I've setup my routes in my react application like so:
// App.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';
// Pages
import Layout from './pages/Layout/Layout';
import Home from './pages/Home/Home';
import CityOverview from './pages/CityOverview/CityOverview';
import GameOne from './pages/GameOne/GameOne';
import PageTwo from './pages/PageTwo/PageTwo';
import PageThree from './pages/PageThree/PageThree';
ReactDOM.render(
<Router history={hashHistory}>
<Route path='/' component={Layout}>
<IndexRoute component={Home}></IndexRoute>
<Route path='/city-overview' component={CityOverview}></Route>
<Route path='/game-one' component={GameOne}></Route>
<Route path='/page-two' component={PageTwo}></Route>
<Route path='/page-three' component={PageThree}></Route>
</Route>
</Router>,
document.getElementById('app')
);
But I'm struggling to navigate from one page to another, for example:
// Home.js hashHistory.push('/city-overview);
The URL changes in the browser but it doesn't actually navigate to that route...
Upvotes: 1
Views: 1236
Reputation: 281754
Starting with react-router 2 you should not use the history
object to do the navigation, you should use the router instead.
static contextTypes: {
router: React.PropTypes.object.isRequired
}
and then navigate like
this.context.router.push(/city-overview');
You should use it like
import React, { PropTypes } from 'react';
class Home extends React.Component {
handleClick = () =>{
this.context.router.push('/city-overview');
}
static contextTypes = {
router: React.PropTypes.object
}
render() {
return (
<div className="flex-container-center">
<button type="button" onClick={this.props.handleClick}>submit</button>
</div>
);
}
}
If your are using react-router version < v2.0 then you should use the history object like
static contextTypes: {
history: React.PropTypes.object.isRequired
}
and then use it like
this.context.history.push('/city-overview');
This works for both hashHistory
and browserHistory
Upvotes: 0
Reputation: 24130
I use contextType
in my component for react-router.
static contextTypes = {
router: React.PropTypes.object.isRequired
};
and to change the route inside the component based on some action -
this.context.router.replace({
pathname : '/'/city-overview',
state : {
// some state data if you need to pass
// key : val
}
});
Upvotes: 1