Handle platform-specific code, accessibility, and debugging on real devices.
Platform Differences
React Native runs on iOS, Android, and Web. Handle differences gracefully.
Platform Detection
import { Platform, View, Text, StyleSheet } from 'react-native';
export function PlatformInfo() {
return (
<View style={styles.container}>
<Text style={styles.label}>OS: {Platform.OS}</Text> // 'ios' | 'android' | 'web'
<Text style={styles.label}>Version: {Platform.Version}</Text> // iOS: '17.0', Android: 34
<Text style={styles.label}>Is iOS: {String(Platform.OS === 'ios')}</Text>
<Text style={styles.label}>Is Android: {String(Platform.OS === 'android')}</Text>
<Text style={styles.label}>Is Web: {String(Platform.OS === 'web')}</Text>
</View>
);
}
// Platform-specific constants
const isIOS = Platform.OS === 'ios';
const isAndroid = Platform.OS === 'android';
const isWeb = Platform.OS === 'web';Platform.select()
import { Platform, StyleSheet, View, Text } from 'react-native';
const styles = StyleSheet.create({
container: {
paddingTop: Platform.select({
ios: 44, // iOS status bar
android: 24, // Android status bar
web: 0,
default: 0,
}),
backgroundColor: Platform.select({
ios: '#ffffff',
android: '#fafafa',
web: '#ffffff',
}),
},
shadow: Platform.select({
ios: {
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 4,
},
android: {
elevation: 4,
},
web: {
boxShadow: '0 2px 4px rgba(0,0,0,0.1)',
},
}),
});
// Platform.select for any value
const fontFamily = Platform.select({
ios: 'SF Pro Display',
android: 'Roboto',
web: 'system-ui',
default: 'system-ui',
});
const buttonText = Platform.select({
ios: 'Done',
android: 'OK',
web: 'Submit',
});Platform-Specific File Extensions
components/
├── Button.tsx # Shared (all platforms)
├── Button.ios.tsx # iOS only
├── Button.android.tsx # Android only
├── Button.native.tsx # iOS + Android (not web)
├── Button.web.tsx # Web only
└── Button.native.web.tsx # Fallback
// Button.tsx - shared interface
export interface ButtonProps {
title: string;
onPress: () => void;
variant?: 'primary' | 'secondary';
}
// Button.ios.tsx - iOS implementation
import { Pressable, Text, StyleSheet } from 'react-native';
export function Button({ title, onPress, variant = 'primary' }: ButtonProps) {
return (
<Pressable onPress={onPress} style={[styles.base, styles[variant]]}>
<Text style={styles.text}>{title}</Text>
</Pressable>
);
}
const styles = StyleSheet.create({
base: { borderRadius: 8, paddingVertical: 12, paddingHorizontal: 24 },
primary: { backgroundColor: '#007aff' },
secondary: { backgroundColor: '#f0f0f0' },
text: { color: 'white', fontWeight: '600', textAlign: 'center' },
});
// Button.web.tsx - Web implementation (can use HTML button)
import { Button as HTMLButton } from 'react-native-web';
export function Button({ title, onPress, variant = 'primary' }: ButtonProps) {
return (
<HTMLButton
onClick={onPress}
className={`btn btn-${variant}`}
>
{title}
</HTMLButton>
);
}Platform-Specific APIs
Haptics
import { Platform, Alert } from 'react-native';
import * as Haptics from 'expo-haptics';
export function triggerHaptic(type: 'light' | 'medium' | 'heavy' | 'success' | 'warning' | 'error' = 'light') {
if (Platform.OS === 'web') return;
switch (type) {
case 'light': Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); break;
case 'medium': Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium); break;
case 'heavy': Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Heavy); break;
case 'success': Haptics.notificationAsync(Haptics.NotificationFeedbackType.Success); break;
case 'warning': Haptics.notificationAsync(Haptics.NotificationFeedbackType.Warning); break;
case 'error': Haptics.notificationAsync(Haptics.NotificationFeedbackType.Error); break;
}
}
// Usage
<Pressable onPress={() => { triggerHaptic('light'); doAction(); }}>
<Text>Tap me</Text>
</Pressable>Share Sheet
import { Share, Platform } from 'react-native';
export async function shareContent(title: string, message: string, url?: string) {
try {
const result = await Share.share({
title,
message,
url,
});
if (result.action === Share.sharedAction) {
console.log('Content shared!');
}
} catch (error) {
console.error('Share failed:', error);
}
}
// Web fallback
if (Platform.OS === 'web' && navigator.share) {
// Use Web Share API
}Clipboard
import { Clipboard } from 'react-native';
export async function copyToClipboard(text: string) {
await Clipboard.setString(text);
// Show toast: "Copied!"
}
export async function pasteFromClipboard(): Promise<string> {
return await Clipboard.getString();
}Back Handler (Android)
import { BackHandler, Platform } from 'react-native';
import { useEffect } from 'react';
export function useBackHandler(handler: () => boolean) {
useEffect(() => {
if (Platform.OS !== 'android') return;
const subscription = BackHandler.addEventListener('hardwareBackPress', handler);
return () => subscription.remove();
}, [handler]);
}
// Usage in screen
export function SettingsScreen() {
const [showModal, setShowModal] = useState(false);
useBackHandler(() => {
if (showModal) {
setShowModal(false);
return true; // Handled, don't exit app
}
return false; // Let default behavior (exit app or go back)
});
return <View>...</View>;
}Accessibility
Make your app usable by everyone, including people with disabilities.
Accessibility Props
import { View, Text, Pressable, StyleSheet, AccessibilityRole, AccessibilityState } from 'react-native';
export function AccessibleButton({
title,
onPress,
disabled = false,
loading = false
}: ButtonProps) {
return (
<Pressable
onPress={onPress}
disabled={disabled || loading}
accessibilityRole="button"
accessibilityState={{
disabled: disabled || loading,
busy: loading,
}}
accessibilityLabel={loading ? 'Loading, please wait' : title}
accessibilityHint={disabled ? 'Button is disabled' : 'Double tap to activate'}
style={[styles.button, disabled && styles.disabled, loading && styles.loading]}
>
{loading ? (
<ActivityIndicator size="small" color="white" />
) : (
<Text style={styles.text}>{title}</Text>
)}
</Pressable>
);
}Screen Reader Support
import { View, Text, Image, StyleSheet } from 'react-native';
export function MovieCard({ title, year, poster, description }: MovieCardProps) {
return (
<View
accessible={true}
accessibilityRole="button"
accessibilityLabel={`${title}, released ${year}. ${description}`}
accessibilityHint="Double tap to view details"
style={styles.card}
>
<Image
source={{ uri: poster }}
style={styles.poster}
accessibilityRole="image"
accessibilityLabel={`${title} movie poster`}
resizeMode="cover"
/>
<View style={styles.content}>
<Text style={styles.title}>{title}</Text>
<Text style={styles.year}>{year}</Text>
</View>
</View>
);
}Accessibility Properties Reference
| Prop | Type | Description |
|---|---|---|
accessible | boolean | Groups children into single element |
accessibilityRole | string | 'button', 'link', 'header', 'image', 'text', 'adjustable', 'search', 'summary' |
accessibilityState | object | { disabled, selected, checked, busy, expanded } |
accessibilityLabel | string | Text read by screen reader |
accessibilityHint | string | Additional context |
accessibilityValue | object | { min, max, now, text } for sliders/progress |
accessibilityActions | array | Custom actions [{ name, label }] |
onAccessibilityAction | function | Handle custom actions |
Dynamic Type (Large Text)
import { useFontScale, Text, StyleSheet } from 'react-native';
export function ScalableText({ children, style, maxScale = 1.3 }: ScalableTextProps) {
const fontScale = useFontScale();
const clampedScale = Math.min(fontScale, maxScale);
return (
<Text style={[style, { fontSize: (style?.fontSize || 16) * clampedScale }]}>
{children}
</Text>
);
}
// Test with: Settings → Accessibility → Display & Text Size → Larger TextVoiceOver / TalkBack Testing
# iOS: Settings → Accessibility → VoiceOver → ON
# Android: Settings → Accessibility → TalkBack → ON
# Test gestures:
# - Swipe right/left: Next/previous element
# - Double tap: Activate
# - Three finger swipe: Scroll
# - Two finger scrub: Dismiss/escapeColor Contrast
// Minimum 4.5:1 for normal text, 3:1 for large text
const colors = {
// ✅ Good contrast
primary: '#1d4ed8', // on white: 8.6:1
onPrimary: '#ffffff',
secondary: '#374151', // on white: 11.4:1
onSecondary: '#ffffff',
// ❌ Bad contrast - avoid
// lightGray: '#9ca3af', // on white: 2.9:1 (FAIL)
// Semantic colors
error: '#dc2626',
success: '#16a34a',
warning: '#ca8a04',
};
// Use system colors that adapt to light/dark
import { useColorScheme } from 'react-native';
export function ThemedComponent() {
const colorScheme = useColorScheme(); // 'light' | 'dark'
const bg = colorScheme === 'dark' ? '#111827' : '#ffffff';
const text = colorScheme === 'dark' ? '#f9fafb' : '#111827';
return <View style={{ backgroundColor: bg }}><Text style={{ color: text }}>Content</Text></View>;
}Debugging on Real Devices
React Native DevTools
# Start with dev client
npx expo start --dev-client
# In terminal:
# - Press 'j' to open debugger (Chrome DevTools)
# - Press 'm' to open dev menu on device
# - Press 'r' to reloadFlipper (Legacy) / React Native DevTools (New)
# Install React Native DevTools (replaces Flipper)
npm install -g @react-native-community/cli
# Or use the web-based debugger
npx react-native start --devtoolsConsole Logs
import { console } from 'react-native';
// Basic logging
console.log('Debug info');
console.warn('Warning!');
console.error('Error:', error);
// Structured logging
console.info('User action', { action: 'login', userId: '123', timestamp: Date.now() });
// Performance marks
console.time('api-call');
const data = await fetchData();
console.timeEnd('api-call'); // Logs: api-call: 245.3msRemote JS Debugging (Hermes)
# For Hermes (default), debugging works differently:
# 1. Start app with: npx expo start --dev-client
# 2. Open chrome://inspect in Chrome
# 3. Click "inspect" on your device
# 4. Use Chrome DevTools normallyNetwork Inspection
# React Native Network Inspector (built into DevTools)
# Or use: react-native-network-logger
# For production debugging, use:
# - Flipper network plugin (legacy)
# - Proxyman / Charles Proxy (system proxy)
# - ReactotronPerformance Profiling
import { Profiler, useCallback } from 'react';
function onRenderCallback(
id: string,
phase: 'mount' | 'update',
actualDuration: number,
baseDuration: number,
startTime: number,
commitTime: number
) {
console.log(`${id} (${phase}): ${actualDuration.toFixed(2)}ms`);
}
export function ProfiledComponent() {
return (
<Profiler id="MovieList" onRender={onRenderCallback}>
<MovieList />
</Profiler>
);
}
// Why Did You Render
import whyDidYouRender from '@welldone-software/why-did-you-render';
MovieList.whyDidYouRender = true;Device Logs
# iOS Simulator
xcrun simctl spawn booted log stream --predicate 'process == "my-app"'
# Physical iOS (requires Xcode)
# Xcode → Window → Devices and Simulators → Select device → Open Console
# Android
adb logcat -s ReactNativeJS:V *:S
# Or use:
# - Android Studio Logcat
# - pidcat (colorized): npm install -g pidcatCommon Debugging Scenarios
| Issue | Debugging Approach |
|---|---|
| White screen | Check console for RedBox/YellowBox errors. Enable Fast Refresh. |
| Layout broken | Use Layout Inspector (DevTools → Elements → select View → inspect flex styles) |
| Slow render | Profiler → Record → Interact → Look for components with high actualDuration |
| Memory leak | Xcode Instruments / Android Studio Profiler → Heap dump → Look for retained objects |
| Network failing | Network tab in DevTools, or proxy with Charles/Proxyman |
| Crash on device | adb logcat or Xcode Organizer → Crashes → symbolicate with dSYM |
Try It
Turn on VoiceOver/TalkBack. Navigate your app. Check: labels, hints, contrast, touch target size (min 48x48dp).
# Test on iOS Simulator
xcrun simctl spawn booted log stream --predicate 'process == "ReactNative"'
# Test on Android
adb logcat -s ReactNativeJS:V *:SMake a screen fully accessible
- Take an existing screen with buttons, images, lists
- Add accessibilityRole, accessibilityLabel, accessibilityHint
- Test with VoiceOver (iOS) or TalkBack (Android)
- Fix any issues: missing labels, confusing order, small touch targets
- Verify Dynamic Type works (large text doesn't break layout)
- Check color contrast ratios
Accessibility isn't optional — it's required for App Store/Play Console approval and reaches 15%+ of users. Test with real screen readers. Use accessibilityRole, accessibilityLabel, accessibilityHint. Support Dynamic Type. Minimum touch target: 48×48dp. Contrast: 4.5:1 for text.
Resources
- React Native Platform Specific Code: https://reactnative.dev/docs/platform-specific-code
- React Native Accessibility: https://reactnative.dev/docs/accessibility
- Expo Haptics: https://docs.expo.dev/versions/latest/sdk/haptics/
- React Native Debugging: https://reactnative.dev/docs/debugging
- Web Content Accessibility Guidelines (WCAG): https://www.w3.org/WAI/standards-guidelines/wcag/