4

The following code snippet is from a simple Todo list which stores information on a local EOS blockchain and has a frontend web interface built on ReactJS. The question is related to ReactJS, specifically the event handler code snippet

saveTodo(e) {
  e.preventDefault();
  this.props.onSubmit(this.state.description)
  this.setState({ description: "" })
}

The full program can be found here...https://github.com/eosasia/eos-todo/blob/master/frontend/src/index.jsx

In the body of the event handler saveTodo(e), there is a line this.props.onSubmit(this.state.description). I would like to know what exactly is going on here?

I am new to ReactJS, and it looks to that the above line of code is somehow setting a property (props) by calling a built-in function onSubmit() with an argument retrieved from the state object. Is this correct? I don’t see how onSubmit() was assigned to props anywhere in this code, but somehow we are able to use it like so: this.props.onSubmit(this.state.description) …. What’s going on here?

Thank you kindly.

P.S. pardon the terminology. I'm not sure if "event handler" or "event listener" is the right word.

kamiss
  • 45
  • 1
  • 5

1 Answers1

3

The TodoForm component takes a property "onSubmit".

That line is simply calling this property (that was passed to it by its parent) and passing in the description ( taken from the state of TodoForm ).

For example:

<TodoForm onSubmit={(description) => alert(description)} />

Read more about props in react here.

Matthew Mallimo
  • 361
  • 2
  • 8
  • Thanks Mathew, in your example, you are implementing the function, which results in an alert(description). However, on the full code in the link, there seems to be no implementation of the function. what happens after this.props.onSubmit(this.state.description) gets called? render() { return(
    ............
    )
    – kamiss Jun 14 '18 at 16:37
  • @kamiss In the full code in the link, if you look in the render function of TodoList, you see that `` So in this case, the onSubmit property is set to be the `addNewTodo` function that is declared in TodoList. If you look, `addNewTodo(description)` takes that same description argument that is passed into the property. – Matthew Mallimo Jun 14 '18 at 17:05
  • Thank you Mathew, i finally understood it! – kamiss Jun 14 '18 at 17:21