One of the things I want to do is to produce a single app that does master-detail properly for both tablets and phones. To do that, I needed to be able to do two things:
- Figure out if I was on a tablet.
- Adapt to the orientation.
In master-detail workflows, you have a list page (the master) and a detail page. They are shown as two separate pages on a phone or on a tablet in portrait mode, but they are shown side-by-side if the device is a tablet in landscape mode.
React Native exposes an object called
Dimensions that gives you all the information you need for this. You use it like this:
It returns something like this:
Platform.js) that gives me the information I need:
I can use this in a standard React Native application like this:
And this produces output like this:
Hold on though. Try to rotate that device – it does not re-render the react tree, which means I don’t have orientation detection. To handle that case, I need to add state to the top level react component that detects the orientation. I use the following:
I store the orientation in the state object, then add an event listener. Whenever the dimensions change (for example, due to an orientation change), the state is changed and that causes a re-render of the entire react tree.
As to why this is important? I can now create a MasterDetail react component that takes the master object and the detail object. In the phone (or tablet in portrait mode), I render a navigation bar plus master list OR the detail page, depending on what is selected. On a tablet in landscape mode, I render a flex layout that combines the master list and detail page. I’ll provide more on this topic in my next blog post.