React: Create a Controlled Form

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
    event.preventDefault()
    this.setState({
      submit:event.state.input
    })
    // change code above this line
  }
  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          { /* change code below this line */ }
            <input value={this.state.input} onChange={this.handleChange} />
          { /* change code above this line */ }
          <button type='submit'>Submit!</button>
        </form>
        { /* change code below this line */ }
        <h1>{this.state.submit}</h1> 
        { /* change code above this line */ }
      </div>
    );
  }
};

why is it not working?

event doesn’t have a state property.

Because of this

handleSubmit(event) {
    event.preventDefault()
    this.setState({
      submit: event.state.input
    })
  }

There are 2 things wrong with this

  1. there is no property state on the event object.
  2. there is a target property, but that returns a dom node

So throw a console.log statement like below, and check the event object. Look for target and you will see how to access it’s value.

handleSubmit(event) {
   console.log(event)
  
    event.preventDefault()
    this.setState({
      submit: event.state.input
    })
  }
1 Like

I think if you re-read the question you’ll realize that what they want is to set the value of the SUBMIT equal to the INPUT.

I hope this helps. :slight_smile:

2 Likes

I figured this but I don’t understand why set submit equal to input , I mean those are two different properties, isn’t it convoluted to make them the same?