NoobOfNoobs
NoobOfNoobs

Reputation: 75

Currying event handlers in React

I am trying to write a (curried?) onChange event handler on a Component that will receive a key argument which will let it know which key in the state object to update. The code won't compile, 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>
    );
  }
}

Upvotes: 7

Views: 3379

Answers (2)

V. Sambor
V. Sambor

Reputation: 13389

I think that in your code you have just forgotten to put the arrow function after initializing first function name:

handleChange = (key) = [!!! HERE - should be an arrow !!!] (event) => {
  console.log(key, event);
}

Try to use this:

handleChange = (key) => (event) => {
  console.log(key, event);
}

So this way your first function which has the param key will return another function with param event.

Upvotes: 2

mrinalmech
mrinalmech

Reputation: 2175

You have to pass both the event as well as the key on the OnChange handler.

Do this

<input onChange={this.handleChange.bind(this,'firstName')} value={this.state.firstName} />

And the onChange should be

 handleChange = (key, event) => {
    console.log(key, event);
  }

This will allow both the event and key to be passed and the function will work.

Upvotes: 3

Related Questions