How to Fix cannot read property preventdefault of undefined

When we try and utilize the preventDefault method in JavaScript, one of the most common situations we are typically trying to stop a submit action coming from a form.

This error is frequently seen when creating a function inside a React.js component. It happens because of an incorrect binding of this. Sometimes the scope is not setup correctly which causes the event object to be undefined.

So, how can you fix the cannout read property preventDefault of undefined error? This can be fixed by using the following methods

  • Not executing the function in the callback handler (most likely culprit)
  • Binding the scope correctly with an arrow function
  • Using JavaScript’s .bind() to set the correct scope.

Let’s demonstrate this using the following example:

function handleClick(e) {
  e.preventDefault();
}

We have our React Button using an empty onClick handler.

 render() {
    return (
      <div>
       <Button onClick={}/>
      </div>
    );
  }

Passing the Event

This is the most likely reason why you are getting this error.

We can pass the event implicity by not calling the function inside the click handler

 <Button onClick={this.handleClick()}/>

This means two things:

  1. There is no event argument is being passed to handleClick, hence the error.
  2. The result of the executed function is being sent instead, which happens to be undefined.

So, don’t call the function in the handler:

 <Button onClick={this.handleClick}/>

This will implicity send over the event as e in functions parameters.

function handleClick(e) {
 e.preventDefault();
}

Using an ES6 arrow function

Additionally, we can use an arrow function bind the context and explicitly send over the event:

<Button onClick={(e) => this.handleClick(e)}/>

Using bind

If you can’t use an arrow function for whatever reason you can also resort to using bind:

<Button onClick={(e) => this.handleClick.bind(this)}/>

Scope and context in React components can be frustrating to debug but thankfully these methods help us problem solve function scopes.

Proudly published with Gatsby