styler styler - 1 month ago 7
React JSX Question

How to set input default value with state and also manually update input?

Very new to React, I have an input that I would like to set with state

quantity
when clicking a button the quantity updates but I also want to be able to manually update the input also which would also update the state value but unsure how to achieve this?

JS

const Input = React.createClass({
getInitialState() {
return {
quantity: 0
}
},

updateQuantity() {
this.setState({
quantity: this.state.quantity + 1
});
},

render() {
return (
<div>
<input type="text" value={this.state.quantity}/>
<button onClick={this.updateQuantity}>Update</button>
</div>
)
}
});


JS Fiddle http://jsfiddle.net/mwvjLqkg/

Answer

You can add onChange event to your input, in order to change quantity manually

const Input = React.createClass({
  getInitialState() {
    return {
      quantity: 0
    }
  },

  updateQuantity() {
    this.setState({
      quantity: this.state.quantity + 1
    });
  },

  handleChange(e) {
    this.setState({ quantity: +e.target.value })
  },

  render() {
    return <div>
      <input 
        type="text" 
        value={this.state.quantity} 
        onChange={ this.handleChange }
      />
      
      <button onClick={this.updateQuantity}>Update</button>
    </div>
  }
});

ReactDOM.render(<Input />, document.body.querySelector('.js-app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div class="js-app"></div>