Reputation: 6709
I have a container component called ButtonContainer
which is passing two bits of state to the button presentational component. The problem is, the container needs to pass an onclick function which uses dispatch
but I don't know how to get access to it. See the code below. How can I get access to dispatch?
import React from 'react'
import { connect } from 'react-redux'
import { fooAction , barAction } from '../foobarActions.js'
import ButtonComponent from './ButtonComponent.jsx'
const mapStateToProps = (state) => {
var buttonText = this.state.foo + this.state.bar
var buttonOnClick = function(e, coord) {
e.preventDefault()
if (e.nativeEvent.which === 1) { // left click
dispatch(fooAction);
} else if (e.nativeEvent.which === 3) {
dispatch(barAction); // right click
} else {
console.log("Unknown click");
}
}
return {
buttonText: buttonText
buttonOnClick: buttonOnClick
}
}
const mapDispatchToProps = (dispatch) => {
return {}
}
const ButtonContainer = connect(
mapStateToProps,
mapDispatchToProps
)(ButtonComponent)
export default ButtonContainer;
Upvotes: 1
Views: 709
Reputation: 6944
It is done in the mapDispatchToProps
function, but you should leave the "which click" logic in the presentational component (ButtonComponent
).
class ButtonComponent extends React.Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
e.preventDefault()
if (e.nativeEvent.which === 1) { // left click
this.props.leftClick();
} else if (e.nativeEvent.which === 3) { // right click
this.props.rightClick();
} else {
console.log("Unknown click");
}
}
render() {
return <button onClick={this.handleClick}>{this.props.buttonText}</button>
}
}
const mapStateToProps = (state) => {
return {
buttonText: this.state.foo + this.state.bar
}
}
const mapDispatchToProps = (dispatch) => {
return {
leftClick: () => dispatch(fooAction),
rightClick: () => dispatch(barAction)
}
}
const ButtonContainer = connect(
mapStateToProps,
mapDispatchToProps
)(ButtonComponent)
export default ButtonContainer;
Upvotes: 2