Skip to content

Latest commit

 

History

History
119 lines (98 loc) · 3.57 KB

README.md

File metadata and controls

119 lines (98 loc) · 3.57 KB

react-router-redux-bind

Build Status Coverage Status Dependencies Status

Redux bindings for React Router Next v4

Installation

npm install --save react-router-redux-bind

Tutorial

A simple example of connecting to redux

import React from 'react'
import { render } from 'react-dom'
import { createStore, applyMiddleware, combineReducers } from 'redux'
import { Provider } from 'react-redux'
import { createBrowserHistory } from 'history'
import { Route } from 'react-router'

import {
  ConnectedRouter,
  routerMiddleware,
  routerReducer as router
} from 'react-router-redux-bind'

import reducers from './reducers'
import routes from './routes'

const history = createBrowserHistory()
const reducers = combineReducers({ ...reducers, router })
const middleware = routerMiddleware(history)
const store = createStore(reducers, applyMiddleware(middleware))

render(
  <Provider store={ store } >
    <ConnectedRouter history={ history } store={ store } routes={ routes } >
      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/topics" component={Topics} />
    </ConnectedRouter>
  </Provider>,
  document.getElementById('content')
)

Actions

import { router } from 'react-router-redux-bind'

store.dispatch(router.push('/'))
store.dispatch(router.replace({ pathname: '/foo/1', search: { from: '/' } }))
store.dispatch(router.go(-2)
store.dispatch(router.goBack()
store.dispatch(router.goForward()

Routes

You can store a react-router match props through passing to ConnectedRouter a simple route config looks like:

export default [
  { path: '/', exact: true, component: require('containers/home') },
  { path: '/topics', component: require('containers/topics') }
  { path: '/topics/:id', component: require('containers/topic') }
]

And after action LOCATION_CHANGE

store.dispatch(router.push('/topics/1'))

expect(store.getState()).toEqual({
  router: {
    location: {
      pathname: '/topics/1'
    },
    match: {
      params: {
        id: '1'
      },
      path: '/topics/:id',
      url: '/topics/1'
    }
  }
})

Server side

Just use <StaticRouter /> and dispatch setLocation action creator, pass request url and route config.

  const routes = require('./routes')
  const { request: { url } } = ctx // koa.js
  store.dispatch(setLocation(url, routes))

Use it with redux-saga

export function* saga() {
  while (true) {
    try {
      const { payload: { match: { path } } } = yield take(LOCATION_CHANGE)
      if (path === '/some') {
        const collection = yield call(fetchSomeCollection)
        yield put(setSomeCollection(collection))
        yield put(router.push('/another'))
      }
    } catch (err) {
      yield call(onError, err)
    }
  }
}