I am currently trying to add an event listener to an application I'm making in react. I'm doing this by hooking into the componentDidMount API, which runs only once the component is rendered and not more than that. My problem is that I'm using connect
from react-redux
to bind my action creators to store.dispatch
. I'm not sure how to bind the event listener to the version of the action creator that is bound to the store with dispatch. Is there a graceful way to do this?
import React, {PropTypes} from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import GridApp from '../components/GridApp';
import * as GridActions from '../actions/gridActions';
class App extends React.Component {
render() {
const { gridAppState, actions } = this.props;
return (
<GridApp gridAppState={gridAppState} actions={actions} />
);
}
componentDidMount() {
console.log("mounted")
// the following line won't be bound to the store here...
document.addEventListener("keydown", GridActions.naiveKeypress );
}
}
function mapStateToProps(state) {
return {
gridAppState: state.gridAppState
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(GridActions, dispatch)
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(App);