Hichem Fellah
Hichem Fellah

Reputation: 37

"TypeError: Cannot read property 'preventDefault' of undefined" in react js

I'm new to react and js in general and i'm following a crash course on react on got stuck on this error at some point of the course I get this error on chrome when i open http://localhost:3000/ even when in the console it says "compiled successfully". i looked arround other topics on the site but none answerd my question

Here is the 2 files concerned

AddTodo.js

export class AddTodo extends Component {  
    onSubmit = (e) => {
      e.preventDefault();
      this.props.addTodo(this.state.title);
      this.setState({ title: '' });
    }
  render() {
    return (
      <form  style = {{display:'flex'}} onSubmit={this.onSubmit()} >
          <input type="text" name='title' style = {{flex:'10' , padding:'5px'}} placeHolder="Ajouter une Tâche..." value={this.state.value} onChange={this.onChange}/> 
          <input type = "submit" value="Ajouter" className="btn" style = {{flex:'1'}} />
      </form>
    )}

App.js

addTodo = (title) => {const newTodo = {id : 5,title,completed : false,}
render() {
return (
  <div className="App">
    <div className="container">
      <Header />
      <AddTodo addTodo ={this.addTodo}/>
      <Todos todos={this.state.todos} markComplete={this.markComplete} delTodo={this.delTodo} />
    </div>
  </div>
);

}

Upvotes: 2

Views: 8908

Answers (3)

David
David

Reputation: 218960

You're executing the function immediately:

onSubmit={this.onSubmit()}

Which means two things:

  1. No event argument is being passed to it, hence the error.
  2. The result of the function is being used as the submit handler, which is also undefined.

Don't execute the function, just pass the function itself as a reference to be executed by the system later, when the form is submitted:

onSubmit={this.onSubmit}

Upvotes: 4

Deepak
Deepak

Reputation: 870

You have issues while assigning the function on onSubmit:

 <form  style = {{display:'flex'}} onSubmit={this.onSubmit} >

As per your code onSubmit={this.onSubmit()}, it doesn't assigns but executes the code with render itself, not on submit.

Upvotes: 1

Radonirina Maminiaina
Radonirina Maminiaina

Reputation: 7004

Replace your onSubmit={this.onSubmit()} with onSubmit={this.onSubmit}, otherwise you can't access the e params.

<form  style = {{display:'flex'}} onSubmit={this.onSubmit} >
   <input type="text" name='title' style = {{flex:'10' , padding:'5px'}} placeHolder="Ajouter une Tâche..." value={this.state.value} onChange={this.onChange}/> 
   <input type = "submit" value="Ajouter" className="btn" style = {{flex:'1'}} />        
</form>

Upvotes: 1

Related Questions