I have a function handleInputChange that I want to write once (DRY principle), but apply it to many of my React classes. However, binding to this in the constructor doesn't work.
handleInputChange = (key, value) => {this.setState(key: value)}
class Login extends Component {
constructor(props) {
super(props);
this.state = {
loginBox: {
username: "",
password: ""}
}
this.handleInputChange = handleInputChange.bind(this) // DOESN't WORK
}}
Why does the above method not work? The error I get is:
Uncaught TypeError: Cannot read property 'setState' of undefined
I am currently using this function wrapper workaround, but I'd rather bind the function directly.
handleInputChange = (_this) => () => (key, value) => {_this.setState(key: value)}
class Login extends Component {
...
this.handleInputChange = (key, value) => handleInputChange(this)(key, value)