Search code examples
javascriptreactjsreduxdispatch

React-Redux - how do I dispatch actions from children components?


I'm using React with Redux and have this issue.

First I'm creating the EditorContainer component that introduces store and renders:

EditorContainer.jsx:

<Provider store={store}> <Editor></Editor> </Provider>

Dispatching actions within EditorContainer.jsx works just fine.

But I want to dispatch some actions in my Editor.jsx also so I do:

Editor.jsx

class Editor extends React.Component {
  componentWillMount() {
    store.dispatch(doSomething());
  }

  render() {
    return (
      // code
    );
  }
}

const mapStateToProps = state => ({
  somethingPayload: somethingPayload
});

export default connect(mapStateToProps)(Editor);

And of course I'm getting Uncaught ReferenceError: store is not defined in line number 3.

Shouldn't connect do the job here and include store & dispatch in Editor component in my case?


Solution

  • You should use this.props.dispatch instead of store.dispatch, because the dispatch function is passed through the props.