Forms

Objectives

  • Describe a controlled component vs uncontrolled

  • Handle a submit using onSubmit

Uncontrolled Component

 <input type="text" />

React is not aware of what the user is typing, the browser is in charge of the state

Controlled Component

 <input type="text" value={this.state.inputText}/>

React is now in control of the state via this.state.inputText, but the input can't be updated

Controlled Component With Update

 <input
   type="text"
   name="inputText"
   value={this.state.inputText}
   onChange={(e) => {
     this.setState({inputText: e.target.value})
   }}
/>

React is now in control of the state via this.state.inputText and the state can change via onChange

onSubmit

<form onSubmit={(e) => {
  e.preventDefault();
  const data = [...this.state.data,
                this.state.inputText];
  this.setState({data, inputText: ''});
}}>
  <input
     type="text"
     name="inputText"
     value={this.state.inputText}
     onChange={(e) => {
       this.setState({[e.target.name]: e.target.value})
     }}
  />
</form>

Common Mistake

<form>
  <input
     type="text"
     name="inputText"
     value={this.state.inputText}
     onChange={(e) => {
       this.setState({[e.target.name]: e.target.value})
     }}
  />
  <button
    onClick={ /* trying to handle submit here */ }
    type="submit"
  >
   SAVE
  </button>
</form>

A button's click is not the same as a submit, use onSubmit