2

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

}

0

3 Answers 3

4

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}
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.