Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 71 ยท Components and Interaction

Platform APIs: Linking, Share, Vibration, Appearance

Use React Native's built-in platform APIs: open links with Linking, share content, vibrate, track AppState, handle the Android back button and ask for permissions.

Components draw things on the screen. Platform APIs do everything else: they ask the phone to open another app, show the share sheet, buzz in your hand, tell you when the app goes to the background, or react to the Android back button. React Native ships a handful of these in the core package, and they are plain JavaScript objects with methods, not components.

In this lesson you meet Linking, Share, Vibration, AppState, BackHandler and Appearance, plus the permission model that sits behind many device features. You will see the real calls, and then run small stand-ins that mimic how each API behaves.

Read-only and stand-in. These APIs talk to iOS and Android, so the real react-native imports are shown in plain code blocks. The TryIts replace the phone with small JavaScript objects that follow the same rules (promises, subscriptions, handler order). They teach the behavior, not the real hardware.

Linking: open URLs and other apps

Linking hands a URL to the operating system, which decides which app should open it. A web address opens the browser, mailto: opens the mail app, tel: opens the dialer, and a custom scheme such as myapp:// opens another app that registered it.

TSX
import { Linking } from 'react-native';

async function openDocs() {
  await Linking.openURL('https://example.com/docs');
}

async function callSupport() {
  const url = 'tel:+15555550123';
  if (await Linking.canOpenURL(url)) {
    await Linking.openURL(url);
  }
}

Linking.openSettings(); // jump to this app's page in the system Settings

Both openURL and canOpenURL return promises. openURL rejects if the system cannot handle the URL, so wrap it in try/catch when the link comes from data you do not control.

Two platform rules matter in practice:

  • On iOS, canOpenURL only answers true for custom schemes you listed in LSApplicationQueriesSchemes in the app's Info.plist. https, mailto and tel work without it.
  • On Android 11 and newer, apps cannot see which other apps are installed unless the manifest declares them in a <queries> block.

With Expo you set these in the app config (see Project Structure and App Config). A missing declaration is the usual reason canOpenURL returns false for an app that is clearly installed.

Linking also works in the other direction. When someone opens a link that points at your app, you read it:

TSX
import { useEffect } from 'react';
import { Linking } from 'react-native';

function useIncomingLinks(onLink: (url: string) => void) {
  useEffect(() => {
    Linking.getInitialURL().then((url) => {
      if (url) onLink(url); // the link that launched the app
    });
    const subscription = Linking.addEventListener('url', (event) => {
      onLink(event.url); // links that arrive while the app is running
    });
    return () => subscription.remove();
  }, [onLink]);
}

getInitialURL covers a cold start, and the url event covers links that arrive while the app is already open. Navigation libraries do this for you, as you will see in Deep Linking and Authentication Flows.

Never pass untrusted text straight into Linking.openURL. A server response could contain a tel: or custom-scheme URL that you did not expect. Check the scheme against an allowlist first.

Share: the system share sheet

Share.share opens the native share sheet so the user can send content to any app that accepts it.

TSX
import { Share } from 'react-native';

async function shareArticle() {
  const result = await Share.share({
    title: 'A good read',
    message: 'This article explains layout in React Native.',
    url: 'https://example.com/layout', // used on iOS
  });

  if (result.action === Share.sharedAction) {
    // the user picked a target
  } else if (result.action === Share.dismissedAction) {
    // the user closed the sheet
  }
}

The result tells you whether the sheet was used or dismissed. It does not tell you where the content went, and on Android you cannot know whether the user finished sending. Treat it as a gentle signal, never as proof for analytics that must be exact. url is an iOS option; on Android, put the link inside message.

Vibration and haptics

Vibration.vibrate() buzzes the device, and Vibration.vibrate([0, 200, 100, 200]) plays a pattern of pauses and buzzes. Two cautions: on iOS the length you request is ignored (the buzz has a fixed length), and Android needs the VIBRATE permission declared in the manifest. For crisp, modern feedback such as a light tick on a toggle, use a haptics library (Expo ships expo-haptics) instead of raw vibration.

AppState: foreground or background

AppState tells you whether the app is visible. The current value is 'active', 'background' or, on iOS only, 'inactive' (a short state, for example while the app switcher or a system alert is on screen).

TSX
import { useEffect } from 'react';
import { AppState } from 'react-native';

useEffect(() => {
  const subscription = AppState.addEventListener('change', (next) => {
    if (next === 'active') refreshData();
    if (next === 'background') saveDraft();
  });
  return () => subscription.remove();
}, []);

Typical uses are refreshing stale data when the user returns, pausing timers and video, and saving a draft before the system may kill the app. Always remove the subscription in the cleanup function, exactly as you would for any effect (see effect cleanup).

BackHandler: the Android back button

Android phones have a back gesture or button; iOS does not, so BackHandler does nothing there. You register a handler for hardwareBackPress. Handlers run from the most recently added to the oldest. The first one that returns true stops the chain; if none does, the default action runs (go back, or leave the app).

TSX
useEffect(() => {
  if (!modalOpen) return;
  const subscription = BackHandler.addEventListener('hardwareBackPress', () => {
    setModalOpen(false);
    return true; // we handled it: do not leave the screen
  });
  return () => subscription.remove();
}, [modalOpen]);

Navigation libraries register their own handlers, so you only need this for custom things such as closing a bottom sheet or asking "discard changes?".

Six APIs, six jobs

Linking Open URLs and read incoming links.
Share Show the system share sheet.
Vibration Buzz the device.
AppState Active, background or inactive.
1 / 2

Appearance in one paragraph

Appearance.getColorScheme() returns 'light', 'dark' or null, and Appearance.addChangeListener reports changes. In components you will almost always use the useColorScheme() hook instead, which re-renders on change. Theming gets its own lesson: Theming and Dark Mode.

Permissions overview

Some features need the user's consent: camera, location, notifications, contacts. The rules are the same on both systems:

  1. Declare the feature in the app config (a usage description string on iOS, a permission entry on Android).
  2. Ask at the moment the feature is needed, with a short reason, not on the first launch.
  3. Handle all three answers: granted, denied, and "denied and do not ask again".

Plain React Native only includes PermissionsAndroid for Android. In practice each library (camera, location, notifications) exposes its own request...Permissions() function and a status, which you meet in Camera, Location and Sensors. Core APIs in this lesson (Linking, Share, AppState, BackHandler) need no permission at all.

Stand-in: a fake Linking

The object below is not the real Linking. It keeps a list of schemes this "phone" can handle and follows the same promise rules: canOpenURL resolves to a boolean, and openURL rejects when nothing can handle the URL.

A fake Linking with canOpenURL and openURL

The custom scheme fancyapp:// fails because the stand-in phone has no app that registered it, just like a real device where the other app is not installed (or not declared in LSApplicationQueriesSchemes on iOS).

Stand-in: AppState and BackHandler order

This stand-in implements the two rules you most often get wrong: subscriptions you must remove, and the newest-handler-first order of BackHandler.

BackHandler order and AppState subscriptions

Read the log from top to bottom. When the modal is open, its handler runs first and the screen handler never hears about the press. After the modal handler is removed, the screen handler takes over again. With no handler left, the default action happens.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. On iOS, why might Linking.canOpenURL return false for a custom scheme of an installed app?

    iOS only lets you check schemes you declared in Info.plist. Android 11+ has a similar rule with the manifest queries block.
  2. 2. Two BackHandler handlers are registered, and both return true. Which one runs when the back button is pressed?

    Handlers run newest first, and the first handler that returns true stops the chain.
  3. 3. What does Share.share's result tell you reliably?

    You get sharedAction or dismissedAction. The destination is private to the system and the target app.
  4. 4. You add an AppState 'change' listener in an effect. What must the cleanup function do?

    addEventListener returns a subscription. Without remove(), the listener keeps running after the component unmounts.

Summary

  • Linking opens URLs (https, mailto, tel, custom schemes) and reads links that open your app; openURL can reject, and canOpenURL needs declarations on iOS and Android 11+.
  • Share.share shows the system share sheet and reports shared or dismissed.
  • Vibration is simple but limited; use a haptics library for polished feedback.
  • AppState reports active, background and iOS-only inactive; BackHandler is Android-only and runs the newest handler first.
  • Every listener returns a subscription: call remove() on cleanup.
  • Ask for permissions at the moment of need and handle denied states.

Next, make your screens usable by everyone in Accessibility in React Native.