Here is an example simple ReactJS example that includes state and a callback.

Screen Shot 2017-08-29 at 5.58.48 AM.png

The constructor
The constructor is where we setup our component state as well as bind any functions we want to pass later to proper context.

Screen Shot 2017-08-29 at 6.00.48 AM.png

Binding

Screen Shot 2017-08-29 at 6.02.16 AM.png

You can read more about binding options and react here.

Passing functions

The next thing that’s important is to look at how you pass bounded function to your component.

Screen Shot 2017-08-29 at 6.04.55 AM.png

The commented out line is the wrong way to do it. When passing functions in react don’t include the () as that will invoke the function instead of passing it. Super common mistake. If you see an error message looking something like this:

Screen Shot 2017-08-29 at 6.06.25 AM.png

Warning: setState(...): Cannot update during an existing state transition

you’ll know you’ve got that problem.

Arrow methods

And the final thing to note is the use of the arrow function for invoking the passed in method.

Screen Shot 2017-08-29 at 6.09.28 AM.png

Arrow function as a shorter syntax than function expression and does not bind its own this. Best used as non method functions.

Links that help
https://facebook.github.io/react/docs/state-and-lifecycle.html

Advertisements