DEV Community

Randy Rivera
Randy Rivera

Posted on • Updated on

React: Creating a Controlled Form

  • FreeCodeCamp in our last challenge showed us that React can control the internal state for certain elements like input and textarea, which makes them controlled components. This applies to other forms elements as well including the regular HTML form element.
  • Here MyForm component is set up with an empty form. As you can see it has the type set to submit indicating it is the button controlling the form. They want us to add the input element in the form and set its value and onChange() attributes like the last post.
class MyForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: '',
      submit: ''
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange(event) {
    this.setState({
      input: event.target.value
    });
  }
  handleSubmit(event) {
    // Change code below this line

    // Change code above this line
  }
  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          {/* Change code below this line */}

          {/* Change code above this line */}
          <button type='submit'>Submit!</button>
        </form>
        {/* Change code below this line */}

        {/* Change code above this line */}
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode
  • We should also call event.preventDefault() in the submit handler, to prevent default form submit behavior which will refresh the web page.
  • Lastly they want us to create an h1 tag after the form which renders the submit value from the component's state.

  • Answer:

class MyForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      input: '',
      submit: ''
    };
    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleChange(event) {
    this.setState({
      input: event.target.value
    });
  }
  handleSubmit(event) {
    event.preventDefault()
    this.setState({
      submit: this.state.input
    })

  }
  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <input value = {this.state.input} onChange = {this.handleChange}/>
          <button type='submit'>Submit!</button>
        </form>
        <h1>{this.state.submit}</h1>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

Discussion (0)