freeCodeCamp Challenge Guide: Create a Controlled Form

Create a Controlled Form


Problem Explanation

Creating a controlled form is the same process as creating a controlled input, except you need to handle a submit event.

Hints

Hint 1

Create a controlled input that stores its value in state, so that there is a single source of truth. This is what you did in the previous challenge. Create an input element, set its value attribute to the input variable located in state. Remember, state can be accessed by this.state. Next, set the input element’s onChange attribute to call the function ‘handleChange’.

Hint 2

Next, create the handleSubmit method for your component. First, because your form is submitting you will have to prevent the page from refreshing. Second, call the setState() method, passing in an object of the different key-value pairs that you want to change. In this case, you want to set submit to the value of the variable input.

Hint 3

Now that your data is being handled in state, we can use this data. Create an h1 element. Inside of your h1 element, put the current value of ‘submit’. Remember, ‘submit’ is located within state so you’ll need to use this.state. Additionally, placing the variable within JSX requires curly braces { } because it is JavaScript.


Solutions

Solution 1 (Click to Show/Hide)
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>
    );
  }
};
47 Likes