Chapter 8. Platform-Specific Code

In Chapter 7 we looked at how to write native modules with separate implementations in Java and Objective-C. This raises two questions: first, do all React Native components have implementations on both iOS and Android? Should they? How should you handle platform-specific implementations in your own code?

Not all components are available on all platforms, and not all interaction patterns are appropriate for all devices. That doesn’t mean you can’t use platform-specific code in your application, though! In this section, we’ll cover platform-specific interface and implementations, as well as strategies for how to incorporate platform-specific components into your cross-platform applications.

Tip

Writing cross-platform code in React Native is not an all-or-nothing endeavor: you can mix cross-platform and platform-specific code in your application, as we’ll do in this section.

iOS- or Android-Only Components

Some components are available only on a specific platform. This includes things like <TabBarIOS> or <ToolbarAndroid>. They’re usually platform-specific because they wrap some kind of underlying platform-specific API. For some components, having a platform-agnostic version doesn’t make sense. For instance, the <ToolbarAndroid> component exposes an Android-specific API for a view type that doesn’t exist on iOS anyway.

Platform-specific components are named with an appropriate suffix: either IOS or Android. If you try to include one on the wrong ...

Get Learning React Native, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.