React - Create a Controlled Form - Using Arrow function fails the tests

Tell us what’s happening:

I cannot seem to pass the test if I use the following code, however, this code gives the desired output.

handleSubmit = (event) => (
    // Change code below this line
    event.preventDefault(),
    this.setState({
      submit: this.state.input
    })
    // Change code above this line
  )

The tests pass AND give the desired output if I use the following code

handleSubmit (event) {
    // Change code below this line
    event.preventDefault();
    this.setState({
      submit: this.state.input
    })
    // Change code above this line
  }

The difference is, in the previous code I’ve used arrow function.

Please help me identify the issue here.

Your code so far

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: this.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>
    );
  }
}

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:121.0) Gecko/20100101 Firefox/121.0

Challenge Information:

React - Create a Controlled Form

If you change code above the comment that says “Change code below this line” or below the comment tha says “Change code above this line”, then the tests will not pass. That’s why the instructions are there.

The test expects the method to be on the prototype.

The tests

assert(
  __helpers.isCalledWithNoArgs(
    'event.preventDefault',
    MyForm.prototype.handleSubmit.toString()
  )
);

MDN: Arrow functions

Note: Class fields are defined on the instance, not on the prototype, so every instance creation would create a new function reference and allocate a new closure, potentially leading to more memory usage than a normal unbound method.

You can see this if you open the browser console on the challenge and check MyForm.prototype

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.