Elger Mensonides
Elger Mensonides

Reputation: 7029

Bind object to multiple events in react

React newbie question here:

I got a search form with multiple filters as checkboxes. Now in react I understand you have to bind the onChange event of the checkbox to an event handler. Since there could be more that 10 checkboxes I would like to put the results of those checkboxes in a filter object like so:

this.state = {
  categoryFilter: {
    hr: false,
    ict: false,
    finance: false,
    sales: false,
    marketing: false
  }
};

Ideally I would like to bind the categoryFilter of the state directly to the component.

Something like:

<MyCheckBox onChange={() => myEventHandler('finance')} label="finance"/>

myEventHandler(name) {
   switch(name) {
case: 'finance':
    this.props.categoryFilter.finance = true;
    this.props.onCategoryChanged();
}
}

Like I said, I'm new to react so there might be much better solutions, but coming from angular, I'm really missing the data binding here.

So the question is how to bind the categoryFilter object to the component, the react way?

Upvotes: 2

Views: 1733

Answers (2)

Rafael Berro
Rafael Berro

Reputation: 2601

Hey, check out this solution provided by the official documentation. The following code uses a single function to handle all of the input changes.

class Reservation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isGoing: true,
      numberOfGuests: 2
    };

    this.handleInputChange = this.handleInputChange.bind(this);
  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  render() {
    return (
      <form>
        <label>
          Is going:
          <input
            name="isGoing"
            type="checkbox"
            checked={this.state.isGoing}
            onChange={this.handleInputChange} />
        </label>
        <br />
        <label>
          Number of guests:
          <input
            name="numberOfGuests"
            type="number"
            value={this.state.numberOfGuests}
            onChange={this.handleInputChange} />
        </label>
      </form>
    );
  }
}

You can try this on CodePen or if you want more details you can check it here.

Upvotes: 2

Facundo Matteo
Facundo Matteo

Reputation: 2517

You could do something like this

<MyCheckBox onChange={myEventHandler.bind(this, 'finance')} label="finance"/>

myEventHandler(name) {
  const newCategoryFilter = Object.assign(
    {},
    this.state.categoryFilter,
    { [name]: !this.state.categoryFilter[name]}
  );

  this.setState({
    categoryFilter: newCategoryFilter,
  });
  this.props.onCategoryChanged();
}

This also handles the case when you uncheck the checkbox.

Upvotes: 1

Related Questions