React - Form (controlled component)

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React

1 - About

HTML form elements work a little bit differently from other DOM elements in React, because form elements naturally keep some internal state.

The React component that renders a form also controls what happens in that form on subsequent user input. An input form element whose value is controlled by React in this way is called a controlled component.

The react forms components input, textarea, select all accept a value attribute that is used to implement a controlled component.

See below:

Check out uncontrolled components where form data is handled by the DOM itself (not react) if:

  • you need to write an very difficult event handler (for every way your data can change)
  • you are converting a preexisting codebase to React,
  • you are integrating a React application with a non-React library.

3 - Element

3.1 - Input

HTML - Input Element

// The controlled component Name
class NameForm extends React.Component {
  constructor(props) {
 
    super(props);
    this.state = {value: 'default'};
 
    // Mandatory binding of this.
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
 
  }
 
  handleChange(event) {
    // toUppercase to enforce it
    this.setState({value: event.target.value.toUpperCase()});
  }
 
  handleSubmit(event) {
    alert('A name was submitted: ' + this.state.value);
    event.preventDefault();
  }
 
  render() {
    return (
      <div>
      <p>Submit your name. It will be always uppercase and for each keystroke, the value attribute will be updated.</p>
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
      </div>
    );
  }
}
 
ReactDOM.render(
  <NameForm />,
  document.getElementById('root')
);
<div id="root"></div>

Advertising

3.2 - textarea

In HTML, a <textarea> element defines its text by its children. In React, a <textarea> uses a value attribute instead. This way, a form using a <textarea> can be written very similarly to a form that uses a single-line input. See section above.

// The controlled component 
class EssayForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: 'Please write an essay about your favorite DOM element.'
    };
 
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
 
  handleChange(event) {
    this.setState({value: event.target.value});
  }
 
  handleSubmit(event) {
    alert('An essay was submitted: ' + this.state.value);
    event.preventDefault();
  }
 
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Name:
          <textarea cols="50" rows="3" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}
 
 
ReactDOM.render(
  <EssayForm />,
  document.getElementById('root')
);
<div id="root"></div>

3.3 - Select

HTML - Select Element

React, instead of using this HTML selected attribute, uses a value attribute on the root select tag. This is more convenient in a controlled component because you only need to update it in one place.

class SelectForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: 'green'};
 
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
 
  handleChange(event) {
    this.setState({value: event.target.value});
  }
 
  handleSubmit(event) {
    alert('Your favorite color is: ' + this.state.value);
    event.preventDefault();
  }
 
  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Pick your favorite color:
          <select value={this.state.value} onChange={this.handleChange}>
            <option value="green">Green</option>
            <option value="red">Red</option>
            <option value="blue">Blue</option>
            <option value="yellow">Yellow</option>
          </select>
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}
 
ReactDOM.render(
  <SelectForm />,
  document.getElementById('root')
);
<div id="root"></div>

4 - Documentation / Reference

web/javascript/react/form.txt · Last modified: 2019/02/16 17:40 by gerardnico