React forms~ - 401-advanced-javascript-aimurphy/seattle-javascript-401n13 GitHub Wiki

In react each element of the form gets a component, a dumb component, while the container handles the values.

controlled component

  • Each input element gets a component of its own: dumb components

  • The container component is responsible for maintaining state.

  • Callback functions handle form events, then use the container’s state to store the form data.

    The callback function is triggered on events, including change of form control values, or on form submission.

    The function then pushes the form values into the local state of the component and the data is then said to be controlled by the component.

    Because we are using the value attribute on the form element, the value displayed will be the value of this.state.value.

  • This gives your component better control over the form control elements and the form data.

uncontrolled component (no dummies)

 class NameForm extends Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    alert('The value is: ' + this.input.value);
    e.preventDefault();
  }

// the <input> component is responsible for storing its state
// ref attribute creates a reference to the DOM node accessible

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

Refs offer a backdoor to the DOM, which might tempt you to use it to do things the jQuery way. Controlled components, on the other hand, are more straightforward — the form data is handled by a React component.

React's composition model lets you organize your React components into smaller reusable code. Each component exists as an independent functional unit and an hierarchy of components can be used to represent a specific feature. This structure works particularly well with forms. You can create custom components for , <textarea>, , etc. and reuse them to compose a FormContainer component.

everything about this came from here

⚠️ **GitHub.com Fallback** ⚠️