CtrlK
CommunityDocumentationLog inGet started
Tessl Logo

tessl/npm-react-native

A framework for building native apps using React

Overall
score

100%

Evaluation100%

1.06x

Agent success when using this tile

Overview
Eval results
Files

platform-apis.mddocs/

React Native Platform APIs

React Native provides comprehensive platform APIs for accessing device information, system state, and platform-specific functionality across iOS and Android.

Installation

npm install react-native

Device Information APIs

Platform

Access platform-specific information and enable conditional code execution.

// ESM
import {Platform} from 'react-native';

// CommonJS
const {Platform} = require('react-native');

// Platform detection
console.log(Platform.OS); // 'ios' | 'android' | 'windows' | 'macos' | 'web'
console.log(Platform.Version); // iOS: '14.0', Android: 30

// iOS specific checks
if (Platform.OS === 'ios') {
  console.log('Running on iOS');
  console.log('Is iPad:', Platform.isPad); // boolean
}

// Platform-specific values
const styles = StyleSheet.create({
  container: {
    marginTop: Platform.OS === 'ios' ? 20 : 0,
    ...Platform.select({
      ios: {
        backgroundColor: 'red',
      },
      android: {
        backgroundColor: 'blue',
      },
      default: {
        backgroundColor: 'gray',
      },
    }),
  },
});

// Platform selection utility
const instructions = Platform.select({
  ios: 'Press Cmd+R to reload',
  android: 'Double tap R on your keyboard to reload',
  default: 'Press F5 to reload',
});

// Version comparisons
if (Platform.Version >= 21) {
  // Android API 21+ specific code
}
interface PlatformStatic {
  // Platform identification
  OS: 'ios' | 'android' | 'windows' | 'macos' | 'web';
  Version: string | number; // iOS: string, Android: number
  
  // iOS specific
  isPad?: boolean;
  isTesting?: boolean;
  
  // Utility methods
  select<T>(specifics: PlatformSelectSpec<T>): T;
}

interface PlatformSelectSpec<T> {
  ios?: T;
  android?: T;
  windows?: T;
  macos?: T;
  web?: T;
  native?: T;
  default?: T;
}

Dimensions

Get device screen and window dimensions with automatic updates on orientation changes.

import {Dimensions} from 'react-native';

// Get current dimensions
const screenData = Dimensions.get('screen');
const windowData = Dimensions.get('window');

console.log('Screen dimensions:', screenData);
// {width: 414, height: 896, scale: 3, fontScale: 1}

console.log('Window dimensions:', windowData);
// {width: 414, height: 818, scale: 3, fontScale: 1}

// Listen for dimension changes
const subscription = Dimensions.addEventListener('change', ({window, screen}) => {
  console.log('New window dimensions:', window);
  console.log('New screen dimensions:', screen);
});

// Clean up listener
return () => subscription?.remove();

// Calculate responsive sizes
const {width: screenWidth, height: screenHeight} = Dimensions.get('window');
const isLandscape = screenWidth > screenHeight;
const isTablet = screenWidth >= 768;

const styles = StyleSheet.create({
  container: {
    width: screenWidth * 0.9,
    height: isTablet ? screenHeight * 0.7 : screenHeight * 0.5,
  },
});

// Hook for reactive dimensions
import {useWindowDimensions} from 'react-native';

function ResponsiveComponent() {
  const {width, height, scale, fontScale} = useWindowDimensions();
  
  return (
    <View style={{
      width: width * 0.8,
      height: height * 0.6,
    }}>
      <Text>Responsive content</Text>
    </View>
  );
}
interface ScaledSize {
  width: number;
  height: number;
  scale: number;
  fontScale: number;
}

interface DimensionsStatic {
  // Get dimensions
  get(dim: 'window' | 'screen'): ScaledSize;
  
  // Event listening
  addEventListener(
    type: 'change',
    handler: (dims: {window: ScaledSize; screen: ScaledSize}) => void
  ): {remove: () => void};
}

interface DimensionsChangeEvent {
  window: ScaledSize;
  screen: ScaledSize;
}

PixelRatio

Access device pixel density information for high-DPI displays and responsive design.

import {PixelRatio} from 'react-native';

// Get pixel ratio
const pixelRatio = PixelRatio.get();
console.log('Device pixel ratio:', pixelRatio); // 2, 3, etc.

// Get font scale
const fontScale = PixelRatio.getFontScale();
console.log('Font scale:', fontScale); // 1, 1.3, etc.

// Convert dp to pixels
const dpValue = 100;
const pixelValue = PixelRatio.getPixelSizeForLayoutSize(dpValue);
console.log(`${dpValue}dp = ${pixelValue}px`);

// Round to nearest pixel
const exactPixel = PixelRatio.roundToNearestPixel(100.4);
console.log('Rounded pixel:', exactPixel); // 100 or 101

// Responsive image sizing
const imageSize = {
  width: PixelRatio.getPixelSizeForLayoutSize(200),
  height: PixelRatio.getPixelSizeForLayoutSize(150),
};

// High DPI image selection
function getImageSource() {
  const ratio = PixelRatio.get();
  if (ratio >= 3) {
    return require('./image@3x.png');
  } else if (ratio >= 2) {
    return require('./image@2x.png');
  } else {
    return require('./image.png');
  }
}

// Pixel-perfect styling
const styles = StyleSheet.create({
  hairlineWidth: {
    borderBottomWidth: StyleSheet.hairlineWidth, // 1 / PixelRatio.get()
  },
  pixelPerfect: {
    width: PixelRatio.roundToNearestPixel(100.7),
    height: PixelRatio.roundToNearestPixel(50.3),
  },
});
interface PixelRatioStatic {
  // Pixel ratio information
  get(): number;
  getFontScale(): number;
  
  // Conversion utilities
  getPixelSizeForLayoutSize(layoutSize: number): number;
  roundToNearestPixel(layoutSize: number): number;
  
  // Constants
  startDetecting?(): void;
  stopDetecting?(): void;
}

DeviceInfo

Access device-specific information and constants.

import {DeviceInfo} from 'react-native';

// Device information (varies by platform)
console.log('Device info:', DeviceInfo);

// Common usage patterns for device detection
const isIOS = Platform.OS === 'ios';
const isAndroid = Platform.OS === 'android';

// Screen size categories
const {width} = Dimensions.get('window');
const isPhone = width < 768;
const isTablet = width >= 768;

// Device capability detection
const pixelRatio = PixelRatio.get();
const isHighDPI = pixelRatio >= 2;

// Platform version checks
const isModernAndroid = Platform.OS === 'android' && Platform.Version >= 23;
const isModernIOS = Platform.OS === 'ios' && parseFloat(Platform.Version) >= 14;
interface DeviceInfoStatic {
  // Device constants and information
  [key: string]: any;
}

System State APIs

AppState

Monitor application state changes (active, background, inactive) and respond to app lifecycle events.

import {AppState} from 'react-native';

// Get current app state
const currentState = AppState.currentState;
console.log('Current app state:', currentState); // 'active' | 'background' | 'inactive'

// Listen for app state changes
const handleAppStateChange = (nextAppState) => {
  console.log('App state changed to:', nextAppState);
  
  if (nextAppState === 'active') {
    // App came to foreground
    console.log('App is now active');
  } else if (nextAppState === 'background') {
    // App went to background
    console.log('App is now in background');
  } else if (nextAppState === 'inactive') {
    // App is transitioning between states (iOS only)
    console.log('App is inactive');
  }
};

// Add event listener
const subscription = AppState.addEventListener('change', handleAppStateChange);

// Remove event listener
subscription.remove();

// React hook for app state
import {useEffect, useState} from 'react';

function useAppState() {
  const [appState, setAppState] = useState(AppState.currentState);
  
  useEffect(() => {
    const subscription = AppState.addEventListener('change', setAppState);
    return () => subscription.remove();
  }, []);
  
  return appState;
}

// Usage in component
function AppStateComponent() {
  const appState = useAppState();
  
  useEffect(() => {
    if (appState === 'active') {
      // Refresh data when app becomes active
      refreshData();
    }
  }, [appState]);
  
  return (
    <View>
      <Text>App State: {appState}</Text>
    </View>
  );
}

// Pause/resume functionality
useEffect(() => {
  const subscription = AppState.addEventListener('change', (nextAppState) => {
    if (nextAppState === 'background') {
      // Pause expensive operations
      pauseAnimations();
      pauseTimers();
    } else if (nextAppState === 'active') {
      // Resume operations
      resumeAnimations();
      resumeTimers();
    }
  });
  
  return () => subscription.remove();
}, []);
type AppStateStatus = 'active' | 'background' | 'inactive';

interface AppStateStatic {
  // Current state
  currentState: AppStateStatus;
  
  // Event listening
  addEventListener(
    type: 'change',
    listener: (state: AppStateStatus) => void
  ): {remove: () => void};
  
  // Legacy methods (deprecated)
  removeEventListener?(type: 'change', listener: Function): void;
}

BackHandler

Handle hardware back button on Android devices.

import {BackHandler} from 'react-native';

// Basic back handler (Android only)
useEffect(() => {
  const backAction = () => {
    Alert.alert('Hold on!', 'Are you sure you want to go back?', [
      {
        text: 'Cancel',
        onPress: () => null,
        style: 'cancel',
      },
      {text: 'YES', onPress: () => BackHandler.exitApp()},
    ]);
    return true; // Prevent default behavior
  };

  const backHandler = BackHandler.addEventListener('hardwareBackPress', backAction);
  
  return () => backHandler.remove();
}, []);

// Navigation back handling
import {useNavigation} from '@react-navigation/native';

function ScreenWithCustomBack() {
  const navigation = useNavigation();
  
  useEffect(() => {
    const backAction = () => {
      if (hasUnsavedChanges) {
        Alert.alert(
          'Unsaved Changes',
          'You have unsaved changes. Are you sure you want to leave?',
          [
            {text: 'Stay', style: 'cancel'},
            {
              text: 'Leave',
              style: 'destructive',
              onPress: () => navigation.goBack(),
            },
          ]
        );
        return true; // Prevent default
      }
      return false; // Allow default behavior
    };

    const backHandler = BackHandler.addEventListener('hardwareBackPress', backAction);
    return () => backHandler.remove();
  }, [navigation, hasUnsavedChanges]);
  
  return <YourScreenContent />;
}

// Exit app confirmation
function useExitAppConfirmation() {
  useEffect(() => {
    const backAction = () => {
      Alert.alert('Exit App', 'Do you want to exit?', [
        {text: 'No', style: 'cancel'},
        {text: 'Yes', onPress: () => BackHandler.exitApp()},
      ]);
      return true;
    };

    const backHandler = BackHandler.addEventListener('hardwareBackPress', backAction);
    return () => backHandler.remove();
  }, []);
}

// Modal back handling
function ModalComponent({visible, onClose}) {
  useEffect(() => {
    if (!visible) return;
    
    const backAction = () => {
      onClose();
      return true; // Handled
    };

    const backHandler = BackHandler.addEventListener('hardwareBackPress', backAction);
    return () => backHandler.remove();
  }, [visible, onClose]);
  
  return (
    <Modal visible={visible}>
      {/* Modal content */}
    </Modal>
  );
}
interface BackHandlerStatic {
  // Event handling
  addEventListener(
    eventName: 'hardwareBackPress',
    handler: () => boolean
  ): {remove: () => void};
  
  // App control
  exitApp(): void;
  
  // Legacy methods (deprecated)
  removeEventListener?(eventName: 'hardwareBackPress', handler: Function): void;
}

Keyboard

Monitor and control keyboard visibility and behavior.

import {Keyboard} from 'react-native';

// Listen for keyboard events
useEffect(() => {
  const keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', (event) => {
    console.log('Keyboard shown:', event.endCoordinates);
    // {screenX, screenY, width, height, duration, easing}
  });
  
  const keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', (event) => {
    console.log('Keyboard hidden:', event.endCoordinates);
  });
  
  const keyboardWillShowListener = Keyboard.addListener('keyboardWillShow', (event) => {
    console.log('Keyboard will show:', event.endCoordinates);
  });
  
  const keyboardWillHideListener = Keyboard.addListener('keyboardWillHide', (event) => {
    console.log('Keyboard will hide:', event.endCoordinates);
  });
  
  return () => {
    keyboardDidShowListener.remove();
    keyboardDidHideListener.remove();
    keyboardWillShowListener.remove();
    keyboardWillHideListener.remove();
  };
}, []);

// Dismiss keyboard
const dismissKeyboard = () => {
  Keyboard.dismiss();
};

<TouchableWithoutFeedback onPress={dismissKeyboard}>
  <View style={styles.container}>
    <TextInput placeholder="Tap outside to dismiss keyboard" />
  </View>
</TouchableWithoutFeedback>

// Keyboard height tracking
function useKeyboardHeight() {
  const [keyboardHeight, setKeyboardHeight] = useState(0);
  
  useEffect(() => {
    const keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', (event) => {
      setKeyboardHeight(event.endCoordinates.height);
    });
    
    const keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => {
      setKeyboardHeight(0);
    });
    
    return () => {
      keyboardDidShowListener.remove();
      keyboardDidHideListener.remove();
    };
  }, []);
  
  return keyboardHeight;
}

// Adjust view for keyboard
function KeyboardAwareComponent() {
  const [bottomPadding, setBottomPadding] = useState(0);
  
  useEffect(() => {
    const keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', (event) => {
      setBottomPadding(event.endCoordinates.height);
    });
    
    const keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => {
      setBottomPadding(0);
    });
    
    return () => {
      keyboardDidShowListener.remove();
      keyboardDidHideListener.remove();
    };
  }, []);
  
  return (
    <View style={[styles.container, {paddingBottom: bottomPadding}]}>
      <TextInput style={styles.input} />
    </View>
  );
}
interface KeyboardEvent {
  endCoordinates: {
    screenX: number;
    screenY: number;
    width: number;
    height: number;
  };
  startCoordinates?: {
    screenX: number;
    screenY: number;
    width: number;
    height: number;
  };
  duration?: number;
  easing?: string;
}

interface KeyboardStatic {
  // Keyboard control
  dismiss(): void;
  
  // Event listeners
  addListener(
    eventName: KeyboardEventName,
    callback: (event: KeyboardEvent) => void
  ): {remove: () => void};
  
  // Legacy methods (deprecated)
  removeListener?(eventName: KeyboardEventName, callback: Function): void;
  removeAllListeners?(eventName: KeyboardEventName): void;
}

type KeyboardEventName = 
  | 'keyboardWillShow'
  | 'keyboardDidShow'
  | 'keyboardWillHide'
  | 'keyboardDidHide'
  | 'keyboardWillChangeFrame'
  | 'keyboardDidChangeFrame';

External Integration APIs

Linking

Handle deep links, URL schemes, and external app integration.

import {Linking} from 'react-native';

// Open external URLs
const openURL = async (url) => {
  try {
    const supported = await Linking.canOpenURL(url);
    if (supported) {
      await Linking.openURL(url);
    } else {
      Alert.alert('Error', `Don't know how to open URL: ${url}`);
    }
  } catch (error) {
    Alert.alert('Error', 'An error occurred');
  }
};

// Open various URL schemes
openURL('https://www.example.com'); // Web browser
openURL('mailto:support@example.com'); // Email client
openURL('tel:+1234567890'); // Phone dialer
openURL('sms:+1234567890'); // SMS
openURL('maps:0,0?q=restaurant'); // Maps app
openURL('fb://profile/123456789'); // Facebook app

// Get initial URL (app launched via deep link)
useEffect(() => {
  const getInitialURL = async () => {
    try {
      const initialUrl = await Linking.getInitialURL();
      if (initialUrl) {
        console.log('App opened with URL:', initialUrl);
        handleDeepLink(initialUrl);
      }
    } catch (error) {
      console.error('Error getting initial URL:', error);
    }
  };
  
  getInitialURL();
}, []);

// Listen for incoming URLs (app already running)
useEffect(() => {
  const handleUrlChange = (event) => {
    console.log('Received URL:', event.url);
    handleDeepLink(event.url);
  };
  
  const subscription = Linking.addEventListener('url', handleUrlChange);
  return () => subscription.remove();
}, []);

// Deep link handler
const handleDeepLink = (url) => {
  const route = url.replace(/.*?:\/\//g, '');
  const [routeName, paramsString] = route.split('?');
  
  // Parse parameters
  const params = {};
  if (paramsString) {
    paramsString.split('&').forEach(param => {
      const [key, value] = param.split('=');
      params[key] = decodeURIComponent(value);
    });
  }
  
  // Navigate based on deep link
  switch (routeName) {
    case 'profile':
      navigation.navigate('Profile', params);
      break;
    case 'product':
      navigation.navigate('Product', {id: params.id});
      break;
    default:
      navigation.navigate('Home');
  }
};

// Custom URL scheme examples
// myapp://profile/123
// myapp://product?id=456&color=red

// Universal links (iOS) and App links (Android)
// https://myapp.com/profile/123
// https://myapp.com/product?id=456

// Check if URL can be opened
const checkURL = async (url) => {
  try {
    const canOpen = await Linking.canOpenURL(url);
    console.log(`Can open ${url}:`, canOpen);
  } catch (error) {
    console.error('Error checking URL:', error);
  }
};

// Open settings
const openSettings = () => {
  Linking.openSettings();
};
interface LinkingStatic {
  // URL handling
  canOpenURL(url: string): Promise<boolean>;
  openURL(url: string): Promise<void>;
  openSettings(): Promise<void>;
  
  // Deep link handling
  getInitialURL(): Promise<string | null>;
  addEventListener(
    type: 'url',
    handler: (event: {url: string}) => void
  ): {remove: () => void};
  
  // Legacy methods (deprecated)
  removeEventListener?(type: 'url', handler: Function): void;
}

interface LinkingEvent {
  url: string;
}

Share

Invoke the native share dialog to share content with other apps.

import {Share} from 'react-native';

// Basic text sharing
const shareText = async () => {
  try {
    const result = await Share.share({
      message: 'Check out this amazing app!',
    });
    
    if (result.action === Share.sharedAction) {
      if (result.activityType) {
        console.log('Shared with activity type:', result.activityType);
      } else {
        console.log('Shared');
      }
    } else if (result.action === Share.dismissedAction) {
      console.log('Share dismissed');
    }
  } catch (error) {
    Alert.alert('Error', error.message);
  }
};

// Share with title (Android)
const shareWithTitle = async () => {
  try {
    await Share.share({
      message: 'Amazing content to share',
      title: 'Share Title', // Android only
    });
  } catch (error) {
    console.error(error);
  }
};

// Share URL
const shareURL = async () => {
  try {
    await Share.share({
      message: 'Check out this website',
      url: 'https://www.example.com', // iOS only
    });
  } catch (error) {
    console.error(error);
  }
};

// Share with options (iOS)
const shareWithOptions = async () => {
  try {
    await Share.share(
      {
        message: 'Content to share',
        url: 'https://example.com',
      },
      {
        // iOS only
        excludedActivityTypes: [
          'com.apple.UIKit.activity.PostToWeibo',
          'com.apple.UIKit.activity.Print',
        ],
        dialogTitle: 'Share this content', // Android only
        subject: 'Email Subject', // Email subject
        tintColor: '#007AFF', // iOS only
      }
    );
  } catch (error) {
    console.error(error);
  }
};

// Share different content types
const shareImage = async (imageUri) => {
  try {
    await Share.share({
      message: 'Check out this image!',
      url: imageUri, // Local file:// or remote https:// URL
    });
  } catch (error) {
    console.error(error);
  }
};

// Share with dynamic content
const shareProduct = async (product) => {
  try {
    const shareContent = {
      message: `Check out ${product.name}: ${product.description}`,
      url: `https://myapp.com/product/${product.id}`,
    };
    
    const shareOptions = {
      dialogTitle: 'Share Product',
      subject: `${product.name} - Product Recommendation`,
    };
    
    await Share.share(shareContent, shareOptions);
  } catch (error) {
    console.error('Share failed:', error);
  }
};

// Component with share functionality
function ShareButton({content, title}) {
  const handleShare = async () => {
    try {
      await Share.share({
        message: content,
        title,
      });
    } catch (error) {
      Alert.alert('Share Failed', 'Unable to share content');
    }
  };
  
  return (
    <TouchableOpacity onPress={handleShare} style={styles.shareButton}>
      <Text>Share</Text>
    </TouchableOpacity>
  );
}
interface ShareContent {
  message?: string;
  title?: string; // Android only
  url?: string; // iOS only
}

interface ShareOptions {
  // iOS only
  excludedActivityTypes?: string[];
  tintColor?: string;
  
  // Android only
  dialogTitle?: string;
  
  // Cross-platform
  subject?: string; // For email
}

interface ShareResult {
  action: 'sharedAction' | 'dismissedAction';
  activityType?: string; // iOS only
}

interface ShareStatic {
  share(content: ShareContent, options?: ShareOptions): Promise<ShareResult>;
  
  // Action constants
  sharedAction: 'sharedAction';
  dismissedAction: 'dismissedAction';
}

System Integration APIs

Appearance

Detect and listen to system appearance changes (light/dark mode).

import {Appearance} from 'react-native';

// Get current color scheme
const colorScheme = Appearance.getColorScheme();
console.log('Current color scheme:', colorScheme); // 'light' | 'dark' | null

// Listen for appearance changes
useEffect(() => {
  const subscription = Appearance.addChangeListener(({colorScheme}) => {
    console.log('Color scheme changed to:', colorScheme);
    updateTheme(colorScheme);
  });
  
  return () => subscription.remove();
}, []);

// Theme context with appearance
const ThemeContext = createContext();

export function ThemeProvider({children}) {
  const [colorScheme, setColorScheme] = useState(Appearance.getColorScheme());
  
  useEffect(() => {
    const subscription = Appearance.addChangeListener(({colorScheme}) => {
      setColorScheme(colorScheme);
    });
    
    return () => subscription.remove();
  }, []);
  
  const theme = {
    colors: colorScheme === 'dark' ? darkColors : lightColors,
    colorScheme,
  };
  
  return (
    <ThemeContext.Provider value={theme}>
      {children}
    </ThemeContext.Provider>
  );
}

// Using appearance in components
function ThemedComponent() {
  const colorScheme = useColorScheme(); // React Native hook
  
  const styles = StyleSheet.create({
    container: {
      backgroundColor: colorScheme === 'dark' ? '#000' : '#fff',
      color: colorScheme === 'dark' ? '#fff' : '#000',
    },
  });
  
  return (
    <View style={styles.container}>
      <Text>Themed content</Text>
    </View>
  );
}

// Dynamic styling based on appearance
const createStyles = (colorScheme) => StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: colorScheme === 'dark' ? '#121212' : '#ffffff',
  },
  text: {
    color: colorScheme === 'dark' ? '#ffffff' : '#000000',
  },
  card: {
    backgroundColor: colorScheme === 'dark' ? '#1e1e1e' : '#f5f5f5',
    borderColor: colorScheme === 'dark' ? '#333333' : '#e0e0e0',
  },
});

function App() {
  const [colorScheme, setColorScheme] = useState(Appearance.getColorScheme());
  
  useEffect(() => {
    const subscription = Appearance.addChangeListener(({colorScheme}) => {
      setColorScheme(colorScheme);
    });
    
    return () => subscription.remove();
  }, []);
  
  const styles = createStyles(colorScheme);
  
  return (
    <View style={styles.container}>
      <Text style={styles.text}>App with dynamic theming</Text>
    </View>
  );
}
type ColorSchemeName = 'light' | 'dark' | null;

interface AppearanceStatic {
  // Current appearance
  getColorScheme(): ColorSchemeName;
  
  // Event listening
  addChangeListener(
    listener: (preferences: {colorScheme: ColorSchemeName}) => void
  ): {remove: () => void};
  
  // Legacy methods (deprecated)
  removeChangeListener?(listener: Function): void;
}

interface AppearancePreferences {
  colorScheme: ColorSchemeName;
}

Network and Storage APIs

I18nManager

Manage internationalization and right-to-left (RTL) layout support.

import {I18nManager} from 'react-native';

// Check RTL status
console.log('Is RTL:', I18nManager.isRTL); // boolean

// Get text direction
console.log('Text direction:', I18nManager.getConstants().isRTL);

// Force RTL (requires app restart)
if (!I18nManager.isRTL) {
  I18nManager.forceRTL(true);
  // App restart required
}

// Allow RTL layout
I18nManager.allowRTL(true);

// RTL-aware styling
const styles = StyleSheet.create({
  container: {
    flexDirection: 'row',
    paddingStart: 20, // Uses paddingLeft in LTR, paddingRight in RTL
    paddingEnd: 10,   // Uses paddingRight in LTR, paddingLeft in RTL
  },
  text: {
    textAlign: I18nManager.isRTL ? 'right' : 'left',
    writingDirection: I18nManager.isRTL ? 'rtl' : 'ltr',
  },
});

// RTL-aware icon direction
function DirectionalIcon({name, style}) {
  const iconName = I18nManager.isRTL ? `${name}-left` : `${name}-right`;
  return <Icon name={iconName} style={style} />;
}

// RTL-aware navigation
function RTLAwareNavigation() {
  const slideDirection = I18nManager.isRTL ? 'right' : 'left';
  
  return (
    <Stack.Navigator
      screenOptions={{
        gestureDirection: I18nManager.isRTL ? 'horizontal-inverted' : 'horizontal',
      }}
    >
      <Stack.Screen name="Home" component={HomeScreen} />
    </Stack.Navigator>
  );
}
interface I18nManagerStatic {
  // RTL state
  isRTL: boolean;
  
  // Configuration
  allowRTL(allowRTL: boolean): void;
  forceRTL(forceRTL: boolean): void;
  swapLeftAndRightInRTL(flipStyles: boolean): void;
  
  // Constants
  getConstants(): {
    isRTL: boolean;
    doLeftAndRightSwapInRTL: boolean;
  };
}

Development and Debug APIs

DevSettings

Access development-time settings and actions (development builds only).

import {DevSettings} from 'react-native';

// Add developer menu item (development only)
if (__DEV__) {
  DevSettings.addMenuItem('Clear Cache', () => {
    // Custom cache clearing logic
    clearAppCache();
  });
  
  DevSettings.addMenuItem('Reset Database', () => {
    Alert.alert(
      'Reset Database',
      'Are you sure?',
      [
        {text: 'Cancel', style: 'cancel'},
        {text: 'Reset', onPress: resetDatabase},
      ]
    );
  });
  
  DevSettings.addMenuItem('Toggle Debug Mode', () => {
    toggleDebugMode();
  });
}

// Reload app programmatically (development only)
const reloadApp = () => {
  if (__DEV__) {
    DevSettings.reload();
  }
};

// Development utilities
function DeveloperTools() {
  if (!__DEV__) return null;
  
  return (
    <View style={styles.devTools}>
      <Button title="Reload" onPress={() => DevSettings.reload()} />
      <Button title="Clear Logs" onPress={clearLogs} />
    </View>
  );
}
interface DevSettingsStatic {
  // Developer menu
  addMenuItem(title: string, handler: () => void): void;
  
  // App control
  reload(): void;
}

This comprehensive documentation covers all the essential platform APIs in React Native, providing developers with the tools needed to create robust, cross-platform mobile applications that integrate seamlessly with device capabilities and system features.

Install with Tessl CLI

npx tessl i tessl/npm-react-native@1000.0.0

docs

animation.md

core-components.md

index.md

native-bridge.md

platform-apis.md

react-hooks.md

styling.md

user-interaction.md

tile.json