Forms – Controlled Components

When we need to process the user's input on-the-fly (with 'onChange' / 'onSubmit'), we should link the value attributesof the input fields to the states of the component.Otherwise,fixing the 'value' attributes to be values other than '', 'null' and 'undefined', makes the input fields immutable ornon-editable.


RESETRUNFULL
Notice how, unlike original HTML DOM, we can use the ‘value’ attribute on the <select> and <textarea> tags.

class Form extends React.Component {
   constructor(props) {
      super(props);
      this.state = {   // follows the names of the input fields
         isGoing: true,
         numberOfGuests: 2,
         flavor: ['lime','coconut'],
         message: 'your comment...'
      };
      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
   }
   handleChange(event) {
      const target = event.target;
      const value = target.type === 'checkbox' ? target.checked
                          :target.tagName === 'SELECT'? [target.value, ...this.state.flavor]
                         :target.value;
      const name = target.name;
      console.log(name, value, target.tagName);
  this.setState({ [name]: value              // ES6 computed property name syntax
  }); } handleSubmit(event) {
   alert('Your favorite flavor is: ' + this.state.flavor);
  event.preventDefault(); } render() {
   return (
    <form onSubmit={this.handleSubmit}>
    <label> Is going:
  <input
  name="isGoing"
  type="checkbox"
  checked={this.state.isGoing}
            onChange={this.handleChange} />
    </label><br /><br />
            <label>Number of guests:
           <input name="numberOfGuests" type="number"
                  value={this.state.numberOfGuests} onChange={this.handleChange} />
            </label><br /><br />
    <label>Pick your favorite flavor:
               <select name="flavor" value={this.state.flavor}
       onChange={this.handleChange} multiple={true}>
                  <option value="grapefruit">Grapefruit</option>
                  <option value="lime">Lime</option>
                  <option value="coconut">Coconut</option>
                  <option value="mango">Mango</option> </select>
            </label><br /><br />
            <label>Message:
               <textarea name="message" value={this.state.message}
                               onChange={this.handleChange} />
            </label>
       <input type="submit" value="Submit" />
        </form>
    );
  }}ReactDOM.render(<Form />, document.querySelector('div'));