React: Create a Controlled Form

React: Create a Controlled Form
0.0 0

#1
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>
    );
  }
};

#2

why is it not working?


#3

I’ve edited your post for readability. When you enter a code block into the forum, precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


#4

event doesn’t have a state property.


#5

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

#6

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: