Skip to content

SimformSolutionsPvtLtd/react-native-haptic-patterns

Repository files navigation

React Native Haptic Patterns - Simform

react-native-haptic-patterns

react-native-haptic-patterns on npm react-native-haptic-patterns downloads react-native-haptic-patterns install size Android iOS MIT

A React Native library for creating and playing customizable haptic feedback patterns on iOS and Android. Supports advanced pattern recording and playback, enabling developers to deliver rich, tactile experiences in their mobile applications.


✨ Features

  • Cross-platform support - Works seamlessly on both iOS and Android
  • Custom haptic patterns - Create your own vibration patterns with precise control
  • Pattern recording & playback - Record and replay complex haptic sequences
  • Core Haptics API - Leverage iOS's advanced haptic engine (iOS 13+)
  • TypeScript support - Full type definitions included
  • Simple API - Easy-to-use methods with Promise-based interface
  • Lightweight - Minimal dependencies and small bundle size

Quick Access

Features | Requirements | Installation | Usage | Methods | Types | Examples | Troubleshooting | License


Requirements

  • React Native >= 0.70.0
  • iOS >= 13.0 (for Core Haptics support)
  • Android API >= 29 (Android 9.0+)

Permissions

Android

Add the following permission to your android/app/src/main/AndroidManifest.xml:

<uses-permission android:name="android.permission.VIBRATE" />

Getting Started

Here's how to get started with react-native-haptic-patterns in your React Native project:

Installation

1. Install the package

npm install react-native-haptic-patterns

Or using Yarn:

yarn add react-native-haptic-patterns

2. Install iOS dependencies

cd ios && pod install && cd ..

Or using npx:

npx pod-install

3. Configure Android permissions

Add the vibration permission to android/app/src/main/AndroidManifest.xml:

<uses-permission android:name="android.permission.VIBRATE" />

Usage

Basic Example

Import and use the library in your React Native app:

import React from 'react';
import { Button, View } from 'react-native';
import { HapticPatterns } from 'react-native-haptic-patterns';

const MyComponent = () => {
  const handlePress = async () => {
    try {
      // Check if device supports haptics
      const isSupported = await HapticPatterns.checkForHapticSupport();

      if (isSupported) {
        // Play a 200ms haptic pattern
        HapticPatterns.playHapticPattern(200);
      } else {
        console.log('Haptics not supported on this device');
      }
    } catch (error) {
      console.error('Haptic error:', error);
    }
  };

  return (
    <View>
      <Button onPress={handlePress} title="Feel the Haptic" />
    </View>
  );
};

Quick Start

import { HapticPatterns } from 'react-native-haptic-patterns';

// Check haptic support
const isSupported = await HapticPatterns.checkForHapticSupport();

// Play a simple haptic pattern
HapticPatterns.playHapticPattern(200); // Vibrate for 200ms

// Stop the current haptic pattern
HapticPatterns.stopHapticPattern();

// Play a recorded pattern
const recordedEvents = [
  { startTime: 0, endTime: 100, isPause: false },
  { startTime: 100, endTime: 200, isPause: true },
  { startTime: 200, endTime: 400, isPause: false },
];

await HapticPatterns.playRecordedPattern(recordedEvents);

Advanced Pattern Example

import {
  HapticPatterns,
  RecordedEventType,
} from 'react-native-haptic-patterns';

const playCustomPattern = () => {
  // Create a custom haptic pattern
  const pattern: RecordedEventType[] = [
    { startTime: 0, endTime: 100, isPause: false }, // Short vibration
    { startTime: 100, endTime: 200, isPause: true }, // Pause
    { startTime: 200, endTime: 400, isPause: false }, // Longer vibration
    { startTime: 400, endTime: 500, isPause: true }, // Pause
    { startTime: 500, endTime: 600, isPause: false }, // Final vibration
  ];

  try {
    HapticPatterns.playRecordedPattern(pattern);
    console.log('Pattern playback completed');
  } catch (error) {
    console.error('Pattern playback error:', error);
  }
};

// Use in different scenarios
const provideSuccessFeedback = () => {
  HapticPatterns.playHapticPattern(50); // Quick tap
};

const provideErrorFeedback = async () => {
  const errorPattern: RecordedEventType[] = [
    { startTime: 0, endTime: 100, isPause: false },
    { startTime: 100, endTime: 150, isPause: true },
    { startTime: 150, endTime: 250, isPause: false },
  ];
  await HapticPatterns.playRecordedPattern(errorPattern);
};

Methods

checkForHapticSupport

checkForHapticSupport(): Promise<boolean>

Checks if the device supports haptic feedback.

Platform behavior:

  • Android: Always returns true as Android devices support haptic feedback through the Vibration API.
  • iOS: Queries the device's Core Haptics capabilities to determine if haptic feedback is supported.

Returns:

  • A Promise that resolves to true if haptics are supported, false otherwise.

playHapticPattern

playHapticPattern(vibrationDuration: number): Promise<void>

Plays a custom haptic pattern for the specified duration.

Parameters:

  • vibrationDuration: Duration of the vibration in milliseconds.

Platform behavior:

  • Android: Uses the Vibration API.
  • iOS: Builds and plays a haptic pattern using Core Haptics.

Returns:

  • A Promise that resolves when the pattern has started playing.

stopHapticPattern

stopHapticPattern(): Promise<void>

Stops the currently playing haptic pattern.

Platform behavior:

  • Android: Cancels vibration.
  • iOS: Stops the HapticEngine player.

Returns:

  • A Promise that resolves when the pattern has been stopped.

playRecordedPattern

playRecordedPattern(recordedEvents: RecordedEventType[]): Promise<void>

Plays a recorded haptic pattern.

Parameters:

  • recordedEvents: An array of recorded haptic or pause events, each with { startTime, endTime, isPause }.

Platform behavior:

  • Android: Converts events to a vibration pattern array and plays it.
  • iOS: Converts events to haptic events and plays them using Core Haptics.

Returns:

  • A Promise that resolves when the entire pattern has finished playing.

Types

RecordedEventType

Represents a single event in a recorded haptic pattern.

interface RecordedEventType {
  startTime: number; // Start time in milliseconds
  endTime: number; // End time in milliseconds
  isPause: boolean; // Whether this is a pause (true) or haptic event (false)
}

Example:

const pattern: RecordedEventType[] = [
  { startTime: 0, endTime: 100, isPause: false }, // Vibrate for 100ms
  { startTime: 100, endTime: 200, isPause: true }, // Pause for 100ms
  { startTime: 200, endTime: 300, isPause: false }, // Vibrate for 100ms
];

Examples

To better understand how to use these methods in a real-world scenario, refer to the following full working example project:

Example App: Demonstrates how to record, play, and reset custom haptic patterns using the library's API in a React Native application.

Common Use Cases

Button Press Feedback

<TouchableOpacity
  onPress={() => {
    HapticPatterns.playHapticPattern(50);
    // Handle button action
  }}>
  <Text>Press Me</Text>
</TouchableOpacity>

Success/Error Notifications

const showSuccessNotification = () => {
  HapticPatterns.playHapticPattern(100); // Single haptic
  // Show success message
};

const showErrorNotification = async () => {
  const errorPattern: RecordedEventType[] = [
    { startTime: 0, endTime: 50, isPause: false },
    { startTime: 50, endTime: 100, isPause: true },
    { startTime: 100, endTime: 150, isPause: false },
  ];
  await HapticPatterns.playRecordedPattern(errorPattern);
  // Show error message
};

Long Press Detection

<TouchableOpacity
  onLongPress={() => {
    HapticPatterns.playHapticPattern(150);
    // Handle long press
  }}>
  <Text>Long Press Me</Text>
</TouchableOpacity>

Troubleshooting

iOS

Haptics not working on simulator

  • Core Haptics only works on physical devices. Test on a real iPhone (iPhone 8 or newer recommended for best haptic support).

Build errors after installation

  • Run cd ios && pod install && cd .. to ensure CocoaPods are properly installed.
  • Clean build folder in Xcode: Product > Clean Build Folder (Shift + Cmd + K)
  • Delete derived data: rm -rf ~/Library/Developer/Xcode/DerivedData

Haptics not working on device

  • Ensure the device supports Core Haptics (iPhone 8 and newer)
  • Check that haptic feedback is enabled in device settings
  • Verify iOS version is 13.0 or higher

Android

Vibration not working

  • Ensure you've added the VIBRATE permission to AndroidManifest.xml
  • Check that vibration is enabled in device settings
  • Some devices may have battery optimization that affects vibration

Build errors

  • Try cleaning the build: cd android && ./gradlew clean && cd ..
  • Delete build folders: rm -rf android/app/build
  • Invalidate caches in Android Studio: File > Invalidate Caches / Restart

Permission denied errors

  • Verify the VIBRATE permission is in the correct location in AndroidManifest.xml
  • Check that the permission is not being removed by other configurations

General

Module not found errors

  • Ensure the package is properly installed: npm install or yarn install
  • Try resetting Metro bundler cache: npx react-native start --reset-cache
  • Rebuild the app completely: npx react-native run-ios or npx react-native run-android

Acknowledgements

This library uses and modifies the iOS implementation from react-native-core-haptics-api for customization.

Find this library useful? ❤️

Support it by joining stargazers for this repository.⭐

Bugs / Feature requests / Feedbacks

For bugs, feature requests, and discussion please use GitHub Issues, GitHub New Feature, GitHub Feedback

🤝 How to Contribute

We'd love to have you improve this library or fix a problem 💪 Check out our Contributing Guide for ideas on contributing.

Awesome Mobile Libraries

License

About

A React Native library to create, record, and play customizable haptic feedback patterns on iOS and Android.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Contributors 4

  •  
  •  
  •  
  •