I used React Native last year to ship a simple app at work, and really enjoyed the developer experience. There seem to have been a lot of changes in the framework since then, and I am trying to get up to speed in my free time by building an app for personal use. I wanted to detect Orientation change in my app, and wanted to document my findings here. I came across 2 different solutions:
Solution 1: Use react-native-orientation package
Using the react-native-orientation package, you can detect orientation change, and also do a bunch of other things such as locking/unlocking to a certain orientation. I have used this successfully in the past with code that looks something like this (after installing the package):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
|
However, as of today, this seems to work on iphone but not on android. I tried to go through the issues list on Github, but could not find a solution that worked for me. This led me to another approach that I ended up using right now.
Solution 2: Use layout event for top level view
Rather than rely on another package, if we add an onLayout handler on the top level view, we can detect orientation change because this gets fired every time the device rotates.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
|
P.S I learned about React Native basics from this Pluralsight course.