Using Decorators in React Native
Now that youโve read about how great decorators are, you must be itching to use them in your React Native app. An excellent use for decorators is binding methods to the scope of the object instance. If youโve read Jay Garciaโs excellent post on using ES6 Arrow functions with React Native, he highlights this issue and proposes a solution of using an arrow function.
Using the @autobind
decorator will do the equivalent of this.fn = this.fn.bind(this);
for a function defined on a class. Letโs see how we would go about using @autobind
or any other decorator in our React Native application.
Setup and npm install {allthethings}
With version 0.22, React Native moved to Babel 6. Unfortunately, one of the breaking changes in the move to a plugin-based architecture was the loss of Decorator support. The status of the issue can be tracked on Babelโs Issue Tracker. Fortunately, in the meantime there is a workaround by Logan Smyth that allows us to use decorators as we did in Babel 5.
- First, we need to install this workaround.
npm install --save babel-plugin-transform-decorators-legacy
- Next, we need to create a
.babelrc
file in the root of our React Native application (where we have our index js files and package.json){ "presets": [ "react-native" ], "plugins": [ "transform-decorators-legacy" ] }
What we have done here is tell babel that we will be using the react-native (default) set of plugins alongside the transform-decorators-legacy
we just installed. Now we can use decorators!
@autobind
Once you have decorators working, it is extremely easy to use @autobind
in our React Native app.
As with everything else, we will need to install the library:
npm install --save autobind-decorator
Before we may have had the following snippet:
Letโs switch it up to use @autobind
:
Conclusion
Decorators are an excellent feature brought over from languages such as Python and Java (known as Annotations). They are used to wrap functionality over existing class functions at design time. I hope this has given you a better understanding of how to use them in React Native apps. If you have some useful decorators you have come across or created yourself, please let me know in the comments below.
Stan Bershadskiy
Related Posts
-
React Navigation and Redux in React Native Applications
In React Native, the question of โhow am I going to navigate from one screen…
-
React Navigation and Redux in React Native Applications
In React Native, the question of โhow am I going to navigate from one screen…