Currying event handlers in React
I am trying to write an event handler (curried?) onChange
On a component that will receive an argument key
that will let it know which key in the state object is being updated. The code won't compile by saying 'key' is not defined
.
class App extends Component {
constructor(props) {
super(props);
this.state = {
firstName: null,
lastName: null
}
this.handleChange = this.handleChange.bind(this);
}
handleChange = (key) = (event) => {
console.log(key, event);
}
render() {
return (
<div>
<form>
<input onChange={this.handleChange('firstName')} value={this.state.firstName} />
<input onChange={this.handleChange('lastName')} value={this.state.firstName} />
</form>
{JSON.stringify(this.state, null, 4)}
</div>
);
}
}
source to share
You have to pass in both event
and key
in the handler OnChange
.
Do it
<input onChange={this.handleChange.bind(this,'firstName')} value={this.state.firstName} />
And OnChange
should be
handleChange = (key, event) => {
console.log(key, event);
}
This will skip both event
and key
and the function will work.
source to share