Form (intensive reading of React official document-09)

Posted by jolinar on Mon, 24 Jan 2022 12:23:36 +0100

Basic introduction to form

Official description: in React, HTML form elements work differently from other DOM elements because form elements usually maintain some internal state s.
give an example

<form>
  <label>
    name:
    <input type="text" name="name" />
  </label>
  <input type="submit" value="Submit" />
</form>

unscramble

The form has the default HTML form behavior. The way to achieve this effect is through controlled components in React.

Controlled components

Definition of controlled component: the React component of the rendered form also controls the operation of the form during user input. The form input elements whose values are controlled by React in this way are called "controlled components".

  • Let the previous example print out the example of the controlled component with the name when submitting
class NameForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: ''};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('Submitted name: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          name:
          <input type="text" value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

unscramble

For the controlled component, the input value is always driven by the state of React, because the value attribute is set on the form, and the initial value is the value in the state. Then, whenever the input value changes, the handlechange function will be called to continuously update the value of the state. Once the state changes, the UI will be re rendered. Therefore, for the controlled component, The value entered is always driven by the state of React.

textarea label

Official description: in React, < textarea > uses the value attribute instead. In this way, the form using < textarea > can be very similar to the form using single line input:

class EssayForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: 'Please write an article about what you like DOM Element article.'
    };

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('Submitted articles: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          article:
          <textarea value={this.state.value} onChange={this.handleChange} />
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

unscramble

The textarea tag is similar in usage to the Input form described above.

select tag

  • What is the select tag used for? Answer: drop down list
<select>
  <option value="grapefruit">Grapefruit</option>
  <option value="lime">Lime</option>
  <option selected value="coconut">Coconut</option>
  <option value="mango">Mango</option>
</select>
  • Select a drop-down menu option in React, not through selected, but through the value attribute
class FlavorForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {value: 'coconut'};

    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleChange(event) {
    this.setState({value: event.target.value});
  }

  handleSubmit(event) {
    alert('What's your favorite flavor: ' + this.state.value);
    event.preventDefault();
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <label>
          Choose the flavor you like:
          <select value={this.state.value} onChange={this.handleChange}>
            <option value="grapefruit">Grapefruit</option>
            <option value="lime">Lime</option>
            <option value="coconut">Coconut</option>
            <option value="mango">Mango</option>
          </select>
        </label>
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

Summary

In general, this makes tags such as < input type = "text" >, < textarea > and < Select > very similar - they all accept a value attribute that you can use to implement controlled components.

  • Official tips
    In the select tab, you can select multiple menu items by default by passing in an array to value.
<select multiple={true} value={['B', 'C']}>

File Input tag

Official description: in HTML, < input type = "file" > allows users to select one or more files from the storage device and upload them to the server, or control them by using the File API of JavaScript.

<input type="file" />

unscramble
The file Input tag is an uncontrolled component because it has a read-only attribute.

Process multiple inputs

Official description: when multiple input elements need to be processed, we can add the name attribute to each element and let the processing function according to event target. The value of name selects the action to be performed.

class Reservation extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isGoing: true,
      numberOfGuests: 2
    };

    this.handleInputChange = this.handleInputChange.bind(this);
  }

  handleInputChange(event) {
    const target = event.target;
    const value = target.type === 'checkbox' ? target.checked : target.value;
    const name = target.name;

    this.setState({
      [name]: value
    });
  }

  render() {
    return (
      <form>
        <label>
          participate in:
          <input
            name="isGoing"
            type="checkbox"
            checked={this.state.isGoing}
            onChange={this.handleInputChange} />
        </label>
        <br />
        <label>
          Number of guests:
          <input
            name="numberOfGuests"
            type="number"
            value={this.state.numberOfGuests}
            onChange={this.handleInputChange} />
        </label>
      </form>
    );
  }
}

unscramble

The name attribute corresponds to the identifier of the Input tag.

  • When updating the status, the above case uses the syntax of ES6 to calculate the attribute name to update the state value corresponding to the given input name.
this.setState({
  [name]: value
});

Why

At the bottom of the key of the object is a string. Name is a variable. What we want to save is the value corresponding to the variable, not the string name.

Controlled input null

Official description: the prop specifying value on the controlled component will prevent the user from changing the input. If you specify value but the input can still be edited, you may accidentally set value to undefined or null.
The following code: the input is initially locked, but becomes editable after a short delay.

ReactDOM.render(<input value="hi" />, mountNode);

setTimeout(function() {
  ReactDOM.render(<input value={null} />, mountNode);
}, 1000);

Alternatives to controlled components

Let's first introduce the disadvantages of controlled components:

  • You need to write event handling functions for each way of data change, and pass all input state s through a React component

  • Alternative: use uncontrolled components, which we will describe later.

Topics: Front-end