Ad

Access Redux Store From Redux-simple-router Children

I'm trying to figure out how to access the redux store from within route so I can dispatch actions from within the route.

Here's what my top level Component looks like:

class App extends Component {
  render() {
    return (
      <div>
         { children }
      </div>
    );
  }
}

My redux-simple-router code looks like:

render(
  <Provider store={store}>
    <Router history={history}>
      <Route path="/" component={App}>
        <IndexRoute component={ Home } />
        <Route path="/example" component={ ExampleRoute } />
      </Route>
    </Router>
  </Provider>,
  rootElement
)

If I dump props from within the ExampleRoute component, I don't have access to the store. Any help appreciated!

Ad

Answer

You should use connect from react-redux to get dispatch and current state from the store. It is outlined in the redux docs here: http://rackt.org/redux/docs/basics/UsageWithReact.html

Here is your Example component:

//...
import { connect } from 'react-redux'
//...

export class Example extends Component {
    render () {
        const { dispatch, thingName } = this.props
        return (
            <button onClick={ () => {
                dispatch(myAwesomeActionCreator())
            }}>{ thingName }</button>
        );
    }
}

export default connect(state => state)(Example)

Some good examples of how to use connect can be found in the react-redux docs: https://github.com/rackt/react-redux/blob/master/docs/api.md#examples

Ad
source: stackoverflow.com
Ad