Skip to content

About

React Native Responsive Library

Resources

Stars

0 stars

Watchers

1 watching

Forks

Repository files navigation

React Native Responsive Library

A comprehensive responsive utility library for React Native applications that helps handle different screen sizes, orientations, and device characteristics.

Features

  • 📱 Device-aware scaling and dimensions
  • 🔄 Orientation support
  • 🌓 Dark/Light mode adaptation
  • ⌨️ Keyboard-aware layouts
  • 📏 Safe area handling
  • 🔤 Dynamic text scaling
  • 🖥️ Multi-window mode support
  • 🔄 RTL support
  • ♿ Accessibility utilities

Installation

As a Local Module

  1. Copy the src directory to your project
  2. Import the utilities in your components:
import responsive from './path/to/src/core';

As a Module Plugin (Development)

  1. In your project's package.json, add a local dependency:
{
  "dependencies": {
    "react-native-responsive": "file:../path/to/this/library"
  }
}
  1. Run:
npm install

Future Module Plugin Usage

Benefits of Using as a Module Plugin

  1. Version Control:

    • Easy version management through npm
    • Semantic versioning support
    • Dependency tracking
  2. Updates and Maintenance:

    • Centralized updates
    • Bug fixes available to all projects
    • Feature additions propagate automatically
  3. Build Optimization:

    • Pre-compiled TypeScript definitions
    • Tree-shaking support
    • Smaller bundle sizes
  4. Development Workflow:

    • Consistent API across projects
    • TypeScript support out of the box
    • Better IDE integration

Publishing as a Module Plugin

  1. Prepare for Publishing:

    # Build the library
    npm run build
    
    # Test the build
    npm test
    
    # Update version
    npm version patch # or minor, or major
  2. Publish to npm:

    # Login to npm
    npm login
    
    # Publish the package
    npm publish
  3. Using in Other Projects:

    # Install from npm
    npm install react-native-responsive
    
    # Import in your code
    import responsive from 'react-native-responsive';

Module Plugin Best Practices

  1. Version Management:

    • Use semantic versioning (MAJOR.MINOR.PATCH)
    • Document breaking changes
    • Maintain a changelog
  2. TypeScript Support:

    • Keep type definitions up to date
    • Export all necessary types
    • Document type usage
  3. Documentation:

    • Keep README.md updated
    • Add JSDoc comments
    • Provide usage examples
  4. Testing:

    • Maintain test coverage
    • Test on different devices
    • Test with different React Native versions
  5. Performance:

    • Optimize bundle size
    • Use proper tree-shaking
    • Minimize dependencies

Module Plugin Considerations

  1. Dependencies:

    • Keep peer dependencies minimal
    • Use exact versions for critical dependencies
    • Document required peer dependencies
  2. Compatibility:

    • Test with different React Native versions
    • Support both old and new React Native features
    • Handle breaking changes gracefully
  3. Maintenance:

    • Regular updates
    • Bug fix releases
    • Security patches
  4. Community:

    • Accept contributions
    • Respond to issues
    • Provide support

Basic Usage

Scaling Dimensions

// Scale a size based on screen width
const scaledSize = responsive.scale(16);

// Scale width and height separately
const scaledWidth = responsive.scaleWidth(100);
const scaledHeight = responsive.scaleHeight(200);

// Get percentage-based dimensions
const width = responsive.widthPercentage(50); // 50% of screen width
const height = responsive.heightPercentage(25); // 25% of screen height

Creating Responsive Styles

const styles = StyleSheet.create({
  container: responsive.createResponsiveStyle({
    padding: 16,
    margin: 8,
    borderRadius: 8
  })
});

Text Scaling

// Scale text size
const fontSize = responsive.fontScale(16);

// Use predefined text styles
const styles = StyleSheet.create({
  title: responsive.getTextStyle('title1', {
    color: '#000000'
  })
});

Safe Area Handling

// Add safe area insets
const styles = responsive.withSafeArea({
  padding: 16
});

// Get safe area insets
const insets = responsive.getSafeAreaInsets();

Dark/Light Mode

// Get adaptive colors
const backgroundColor = responsive.adaptiveColor('#FFFFFF', '#000000');

// Create adaptive styles
const styles = responsive.withAdaptiveColors(
  { backgroundColor: '#FFFFFF' },
  { backgroundColor: '#000000' }
);

Configuration

Configure the responsive behavior:

responsive.configure({
  baseWidth: 375, // iPhone X width
  baseHeight: 812, // iPhone X height
  enableOrientation: true,
  widthFactor: 1,
  heightFactor: 1,
  fontScaleFactor: 0.9,
  allowTextScaling: true,
  tabletWidthFactor: 0.8,
  tabletHeightFactor: 0.8,
  splitScreenEnabled: true,
  flipStylesInRTL: true,
  adjustForKeyboard: true,
  multiWindowThreshold: 0.75
});

Device Information

Get device characteristics:

const deviceInfo = responsive.deviceInfo;

// Access device properties
const isTablet = deviceInfo.isTablet;
const isPortrait = deviceInfo.isPortrait;
const screenWidth = deviceInfo.width;
const screenHeight = deviceInfo.height;

API Reference

Core Functions

  • scale(size: number): Scale a size based on screen width
  • scaleWidth(size: number): Scale width dimension
  • scaleHeight(size: number): Scale height dimension
  • fontScale(size: number, respectDeviceSettings?: boolean): Scale font size
  • moderateScale(size: number, factor?: number): Scale with moderation factor
  • widthPercentage(percentage: number): Get percentage of screen width
  • heightPercentage(percentage: number): Get percentage of screen height

Style Utilities

  • createResponsiveStyle(styles: Record<string, any>): Create responsive styles
  • responsiveDimensions(width: number, height: number): Get scaled dimensions
  • spacing(multiplier?: number): Get consistent spacing
  • withSafeArea(style?: Record<string, any>, sides?: Array<'top' | 'bottom' | 'left' | 'right'>): Add safe area insets
  • withRTL(styles: Record<string, any>): Handle RTL layouts
  • withKeyboardAware(normalStyles: Record<string, any>, keyboardVisibleStyles: Record<string, any>): Handle keyboard visibility

Device Utilities

  • getDeviceInfo(): Get current device information
  • getFoldableAdjustedDimensions(): Get dimensions adjusted for foldable devices
  • getKeyboardAdjustedHeight(): Get height adjusted for keyboard
  • isDeviceRotating(): Check if device is rotating

Text Utilities

  • dynamicTypeSize(style: keyof TextStyles, respectDeviceSettings?: boolean): Get dynamic type size
  • getTextStyle(size: number | keyof TextStyles, additionalStyles?: Record<string, any>): Get text style

Color Utilities

  • adaptiveColor(lightModeColor: string, darkModeColor: string): Get adaptive color
  • withAdaptiveColors(lightModeStyles: Record<string, any>, darkModeStyles: Record<string, any>): Get adaptive styles
  • getColorScheme(): Get current color scheme

Contributing

This library is open for contributions. Feel free to submit issues and pull requests.

License

MIT

Practical Examples and Problem Solving

1. Responsive Layout Grid

import { View, StyleSheet } from 'react-native';
import responsive from './core';

const GridExample = () => {
  const styles = StyleSheet.create({
    container: responsive.createResponsiveStyle({
      flex: 1,
      padding: responsive.spacing(2)
    }),
    row: {
      flexDirection: 'row',
      marginBottom: responsive.spacing(2)
    },
    // Responsive grid items
    gridItem: {
      width: responsive.widthPercentage(48), // 48% of screen width
      height: responsive.scaleHeight(100),
      marginHorizontal: responsive.widthPercentage(1), // 1% margin
      backgroundColor: responsive.adaptiveColor('#F5F5F5', '#333333'),
      borderRadius: responsive.scale(8)
    }
  });

  return (
    <View style={styles.container}>
      <View style={styles.row}>
        <View style={styles.gridItem} />
        <View style={styles.gridItem} />
      </View>
      <View style={styles.row}>
        <View style={styles.gridItem} />
        <View style={styles.gridItem} />
      </View>
    </View>
  );
};

Problem Solved: Creates a responsive grid that:

  • Adapts to different screen sizes
  • Maintains proper spacing
  • Handles dark/light mode
  • Works on both phones and tablets

2. Responsive Form Elements

import { View, TextInput, StyleSheet } from 'react-native';
import responsive from './core';

const FormExample = () => {
  const styles = StyleSheet.create({
    container: responsive.withSafeArea({
      flex: 1,
      padding: responsive.spacing(2)
    }),
    input: {
      ...responsive.getTextStyle('body'),
      height: responsive.scale(44),
      borderWidth: responsive.scale(1),
      borderColor: responsive.adaptiveColor('#CCCCCC', '#666666'),
      borderRadius: responsive.scale(8),
      paddingHorizontal: responsive.spacing(2),
      marginBottom: responsive.spacing(2)
    },
    label: {
      ...responsive.getTextStyle('callout'),
      marginBottom: responsive.spacing(1),
      color: responsive.adaptiveColor('#333333', '#CCCCCC')
    }
  });

  return (
    <View style={styles.container}>
      <Text style={styles.label}>Email</Text>
      <TextInput 
        style={styles.input}
        placeholder="Enter your email"
        placeholderTextColor={responsive.adaptiveColor('#999999', '#666666')}
      />
    </View>
  );
};

Problem Solved: Creates form elements that:

  • Scale appropriately on all devices
  • Maintain proper touch target sizes
  • Adapt to system font settings
  • Handle safe areas
  • Support dark/light mode

3. Responsive Card Component

import { View, Text, Image, StyleSheet } from 'react-native';
import responsive from './core';

const CardExample = () => {
  const styles = StyleSheet.create({
    card: {
      ...responsive.responsiveDimensions(300, 400),
      backgroundColor: responsive.adaptiveColor('#FFFFFF', '#1A1A1A'),
      borderRadius: responsive.scale(12),
      padding: responsive.spacing(2),
      margin: responsive.spacing(2),
      shadowColor: '#000',
      shadowOffset: {
        width: 0,
        height: responsive.scale(2)
      },
      shadowOpacity: 0.25,
      shadowRadius: responsive.scale(3.84),
      elevation: responsive.scale(5)
    },
    image: {
      width: '100%',
      height: responsive.scale(200),
      borderRadius: responsive.scale(8),
      marginBottom: responsive.spacing(2)
    },
    title: {
      ...responsive.getTextStyle('title2'),
      color: responsive.adaptiveColor('#000000', '#FFFFFF'),
      marginBottom: responsive.spacing(1)
    },
    description: {
      ...responsive.getTextStyle('body'),
      color: responsive.adaptiveColor('#666666', '#AAAAAA')
    }
  });

  return (
    <View style={styles.card}>
      <Image 
        source={{ uri: 'https://example.com/image.jpg' }}
        style={styles.image}
      />
      <Text style={styles.title}>Card Title</Text>
      <Text style={styles.description}>
        This is a responsive card that adapts to different screen sizes and themes.
      </Text>
    </View>
  );
};

Problem Solved: Creates cards that:

  • Scale proportionally
  • Maintain proper aspect ratios
  • Adapt shadows and elevation
  • Handle text scaling
  • Support dark/light mode

4. Responsive Navigation Header

import { View, Text, StyleSheet, StatusBar } from 'react-native';
import responsive from './core';

const HeaderExample = () => {
  const styles = StyleSheet.create({
    header: {
      ...responsive.withSafeArea({
        backgroundColor: responsive.adaptiveColor('#FFFFFF', '#000000'),
        paddingTop: responsive.spacing(2),
        paddingBottom: responsive.spacing(2),
        borderBottomWidth: responsive.scale(1),
        borderBottomColor: responsive.adaptiveColor('#EEEEEE', '#333333')
      }, ['top'])
    },
    title: {
      ...responsive.getTextStyle('title1'),
      color: responsive.adaptiveColor('#000000', '#FFFFFF'),
      textAlign: 'center'
    },
    statusBar: {
      height: StatusBar.currentHeight,
      backgroundColor: responsive.adaptiveColor('#FFFFFF', '#000000')
    }
  });

  return (
    <>
      <View style={styles.statusBar} />
      <View style={styles.header}>
        <Text style={styles.title}>App Title</Text>
      </View>
    </>
  );
};

Problem Solved: Creates headers that:

  • Handle safe areas properly
  • Adapt to status bar height
  • Scale text appropriately
  • Support dark/light mode
  • Work on different devices

5. Responsive Modal

import { Modal, View, Text, StyleSheet, TouchableOpacity } from 'react-native';
import responsive from './core';

const ModalExample = ({ visible, onClose }) => {
  const styles = StyleSheet.create({
    modal: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor: 'rgba(0, 0, 0, 0.5)'
    },
    content: {
      ...responsive.responsiveDimensions(300, 400),
      backgroundColor: responsive.adaptiveColor('#FFFFFF', '#1A1A1A'),
      borderRadius: responsive.scale(16),
      padding: responsive.spacing(3)
    },
    title: {
      ...responsive.getTextStyle('title2'),
      color: responsive.adaptiveColor('#000000', '#FFFFFF'),
      marginBottom: responsive.spacing(2)
    },
    button: {
      ...responsive.getAccessibleTouchTarget({
        backgroundColor: responsive.adaptiveColor('#007AFF', '#0A84FF'),
        borderRadius: responsive.scale(8),
        padding: responsive.spacing(2),
        alignItems: 'center'
      })
    },
    buttonText: {
      ...responsive.getTextStyle('callout'),
      color: '#FFFFFF'
    }
  });

  return (
    <Modal
      visible={visible}
      transparent
      animationType="fade"
    >
      <View style={styles.modal}>
        <View style={styles.content}>
          <Text style={styles.title}>Modal Title</Text>
          <TouchableOpacity 
            style={styles.button}
            onPress={onClose}
          >
            <Text style={styles.buttonText}>Close</Text>
          </TouchableOpacity>
        </View>
      </View>
    </Modal>
  );
};

Problem Solved: Creates modals that:

  • Scale appropriately on all devices
  • Maintain proper touch targets
  • Handle safe areas
  • Support dark/light mode
  • Provide proper accessibility

Common Responsiveness Problems Solved

  1. Screen Size Adaptation

    • Problem: Components look too large on small screens or too small on large screens
    • Solution: Use scale, scaleWidth, and scaleHeight for proportional scaling
  2. Text Scaling

    • Problem: Text becomes unreadable on different devices
    • Solution: Use fontScale and dynamicTypeSize for proper text scaling
  3. Safe Area Handling

    • Problem: Content hidden behind notches or system UI
    • Solution: Use withSafeArea to respect safe areas
  4. Orientation Changes

    • Problem: Layout breaks when device rotates
    • Solution: Use responsiveDimensions and percentage-based layouts
  5. Accessibility

    • Problem: Touch targets too small on some devices
    • Solution: Use getAccessibleTouchTarget for proper sizing
  6. Dark/Light Mode

    • Problem: Colors don't adapt to system theme
    • Solution: Use adaptiveColor and withAdaptiveColors
  7. RTL Support

    • Problem: Layout breaks in RTL languages
    • Solution: Use withRTL for proper RTL handling
  8. Keyboard Handling

    • Problem: Content hidden behind keyboard
    • Solution: Use withKeyboardAware for keyboard-aware layouts

About

React Native Responsive Library

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors