Search code examples
reactjsjsxreact-dom

Can't Change values of Siblings Reciprocally in ReactJS


I have a component with two fields, it is a converter. It converts between lbs and kg. I am trying to write a component in which whatever input the user changes i.e lbs or kg, the other input fields updates based upon it. The code is working for a single input. the first input you choose to manipulate updates the other fine, but if you change the other one, it does not work.

What am I doing wrong..

Code Pen URL : http://codepen.io/chesshouse/pen/zZOgVG

HTML code:

<div id="app"></div>

JS Code:

var Converter = React.createClass({
  getInitialState: function() {
    return {};
  },

  _calc: function (event) {
    if (event.target.name === 'lbs'){
      this.setState({
        kg: this.convertToKG(event.target.value),
      });
    } else {
      this.setState({
        lbs: this.convertToLBS(event.target.value),
      });
    }
  },

  convertToLBS: function ( kg ) {
    var lbs;
    lbs = parseInt( kg ) * 2.2046226218;
    return lbs;
  },

  convertToKG: function ( lbs ) {
    var kg;
    kg = parseInt( lbs ) / 2.2046226218;
    return kg;
  },

  render: function() {
    return (
      <div>
        <label>LBS
          <input type="text" name="lbs" onChange={this._calc} value={this.state.lbs} />
        </label>
        <label>Kg
          <input type="text" name="kg" onChange={this._calc} value={this.state.kg} />
        </label>

      </div>
    );
  }
});

ReactDOM.render(
  <Converter />,
  document.getElementById('app'),
);

Solution

  • The body of your _calc function only sets one value; given that you have controlled inputs, you need to explicitly update each value when an input is changed.

    By adding 2 lines to _calc you can update the values of both attributes:

      _calc: function (event) {
        if (event.target.name === 'lbs'){
          this.setState({
            lbs: event.target.value, // Add this
            kg: this.convertToKG(event.target.value),
          });
        } else {
          this.setState({
            lbs: this.convertToLBS(event.target.value),
            kg: event.target.value // Add this
          });
        }
      },
    

    Working pen: http://codepen.io/oliverfencott/pen/MpWamo?editors=0010