What I want is to change the route when user clicks a button.
The code is very similar to real-world sample and all the steps introduced in react-router-redux are followed.
reducer/index.js:
import { combineReducers } from 'redux'
import { routerReducer as routing } from 'react-router-redux'
import entities from './entities'
const rootReducer = combineReducers({
entities,
routing
})
export default rootReducer
index.js:
import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import browserHistory from 'react-router/lib/browserHistory'
import syncHistoryWithStore from 'react-router-redux/lib/sync'
import Root from './src/web/containers/Root'
import configureStore from './src/store/configureStore'
const store = configureStore()
const history = syncHistoryWithStore(browserHistory, store)
render(
<Root store={store} history={history} />,
document.getElementById('root')
)
Root.js:
import React, { Component, PropTypes } from 'react'
import { Provider } from 'react-redux'
import routes from '../routes'
import Router from 'react-router/lib/Router'
export default class Root extends Component {
render() {
const { store, history } = this.props
return (
<Provider store={store}>
<div>
<Router history={history} routes={routes} />
</div>
</Provider>
)
}
}
Root.propTypes = {
store: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
}
routes.js:
import React from 'react'
import Route from 'react-router/lib/Route'
import App from './containers/App'
export default (
<Route path="" component={App}>
{/* Other routes */}
</Route>
)
configureStore.js:
import { createStore, applyMiddleware, compose } from 'redux'
import thunk from 'redux-thunk'
import rootReducer from '../reducers'
import { apiMiddleware } from 'redux-api-middleware';
import {routerMiddleware, routerReducer} from 'react-router-redux'
import browserHistory from 'react-router/lib/browserHistory'
const createStoreWithMiddleware = applyMiddleware(apiMiddleware) (createStore);
export default function configureStore(preloadedState) {
const store = createStore(
rootReducer,
preloadedState,
compose(
applyMiddleware(
apiMiddleware,
routerMiddleware(browserHistory),
thunk,
),
)
)
return store
}
Then I want to use push
in a page like this:
import { push } from 'react-router-redux'
class Test extends Component {
render() {
return (
<button onClick={()=>push('/path')}>Test</button>
)
}
}
But Nothing happens, without showing error.
The issue seems to be your component 'Test'.
You have to provide the store's dispatch function to that component in order for the push to make changes.
import { push } from 'react-router-redux';
import { connect } from 'react-redux';
@connect()
class Test extends Component {
render() {
// Provide component with dispatch function
const { dispatch } = this.props;
return (
<button onClick={() => dispatch(push('/path'))}>
Test
</button>
)
}
}