Why do we need to add event.preventDefault?

There is no difference when I remove away the line of " event.preventDefault()" and add it on again, could you show me an example of this? Thanks!

  **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
  this.setState({
    submit: this.state.input
  })
  event.preventDefault()
  // 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_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36

Challenge: Create a Controlled Form

Link to the challenge:

It is not React specific.
Default action for submitting the form is to redirect to the address in the form’s “action” attribute. By using .preventDefault() we’re, well, preventing this default action.

Here’s a working example: https://codepen.io/jenovs/pen/JjMQEvz?editors=1010

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