Basics of Form Handling

Defining Controlled Components

  • Managing form elements in ordinary JavaScript and HTML can become complicated and tedious
  • In React, we can control form elements, which includes:

    • Input elements
    • Text field elements
    • Form submission elements
  • We can do this using controlled components in React

Creating a Controlled Component for Input

  • By using controlled components, the state in React represents a single source of truth for input elements
  • In the example below, the username is a state property
  • It is assigned as the value attribute of our input element
  • Whenever the value is updated by a user, the new value is propagated to the changeUser callback
  • This callback then sets the username to the new value
class Form extends Component {
  constructor(props) {
    super(props);
    this.state = {
      username: ''
    }
  }

  changeUser = (event) => {
    this.setState({
      username: event.target.value
    })
  }

  render() {
    return(
      <form>
        <div>
          <label>Username</label>
          <input
            type="text"
            value={this.state.username}
            onChange={this.changeUser}
          />
        </div>
      </form>
    )
  }
}

Adding a Controlled Component for Submission

class Form extends Component {
  ...

  handleSubmit = event => {
    console.log(`${this.state.username}`); 
    event.preventDefault(); 
  }

  render() {
    <form onSubmit={this.handleSubmit}>
      ...
      <button type="submit">Submit</button>
    </form
  }
}

References

Previous
Next

Styling and CSS

Mounting Lifecycle Methods