jeudi 17 août 2017

Simplifying repeated code in React

It there a best practice to simplify something like the following in React?

getInitialState: function () {
  return {
    checkbox1: false,
    checkbox2: false,
    checkbox3: false,
    ...
  };
},

selectCheckbox1: function () {
  this.setState({
    checkbox1: !this.state.checkbox1
  });
},

selectCheckbox2: function () {
  this.setState({
    checkbox2: !this.state.checkbox2
  });
},

selectCheckbox3: function () {
  this.setState({
    checkbox3: !this.state.checkbox3
  });
},

...

render: function () {
  return (
    <div>
      <input type="checkbox" checked={this.state.checkbox1} onChange={this.selectCheckbox1} />
      <input type="checkbox" checked={this.state.checkbox2} onChange={this.selectCheckbox2} />
      <input type="checkbox" checked={this.state.checkbox3} onChange={this.selectCheckbox3} />
      ...
    </div>
  );
}

For example, I can use an array for the state instead of individual fields and create a generic function that takes an index parameter to distinguish which checkbox to update:

const Checkboxes = React.createClass({
  getInitialState: function () {
    return {
      checkboxes: [false, false, false, ...]
    };
  },

  selectCheckbox: function (index) {
    let checkboxes = this.state.checkboxes.slice();
    checkboxes[index] = !checkboxes[index];
    this.setState({
      checkboxes: checkboxes
    });
  },

  render: function () {
    return (
      <div>
        <input type="checkbox" checked={this.state.checkboxes[0]} onChange={() => this.selectCheckbox(0)} />
        <input type="checkbox" checked={this.state.checkboxes[1]} onChange={() => this.selectCheckbox(1)} />
        <input type="checkbox" checked={this.state.checkboxes[2]} onChange={() => this.selectCheckbox(2)} />
        ...
      </div>
    );
  }
});

I am new to React and JavaScript so I don't know exactly the tradeoffs happening behind the scenes here. Is the second an improvement over the first? Which is preferred and why?

Aucun commentaire:

Enregistrer un commentaire