binding-functions-in-react-component.s
Last updated
Last updated
Note: Please create an or even a Pull Request with your feedback, typo correction.
During this standard, we will take an example from the egghead react native tutorial when launching an event with a submit button.
The tutorial does it the old ES5 way when we should better use the ES6 way (with arrow functions).
Have react-native installed (npm i -g react-native-cli
) (~2 min)
Have a react-native project (react-native init <project name
) (~2 min)
When using the TextInput onChange, the tutorial tells you to define an handleChange function this way (CAUTION, this is a BAD EXAMPLE):
This is bad in two ways: performance and syntax.
Performance: the first problem here is we use bind
at every onChange
event, which is very costly. What we could do is (still not optimal):
we improve our performance, as we only bind at the creation of the class. This is not ideal though.
The bind
function is used to be sure to use the good context (the this
of the class, not the one of the handleChange function).
We can improve the syntax by using an arrow function, which has no proper context and uses the context of the class (you can use tis example).
The this
inside the arrow function handleChange
now refers to the Test
class.