Skip to content

Dynamic forms

Wei edited this page Apr 30, 2019 · 2 revisions

  1. The form’s structure is similar to those of the usual HTML forms. However, each input element gets a component of its own, which we call dumb components. The container component is responsible for maintaining the state. The difference is, we're using a callback function to handle form events and then using the container’s state to store the form data.
  • Because we are using the value attribute on the form element, the value displayed will be the value of this.state.value.
  1. There is another technique, popularly known as uncontrolled components, for creating input forms. This is more like traditional HTML forms because the input form data is stored inside the DOM and not within the component. Elements like and <textarea> maintain their own state, which they update when the input values change. You can query the DOM for the value of an input field using a ref.

Uncontrolled form

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();
  }

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

React recommends using controlled components over refs to implement forms. 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.

import React, { Component } from 'react';  
import './styles.css';  
import FormContainer from './containers/FormContainer';

class App extends Component {  
  render() {
    return (
      <div className="container">
        <h3>React Form</h3>
        <FormContainer />
      </div>
    );
  }
}

export default App; 

Clone this wiki locally