How to Create Vibrations in React Native

Vibrations can be used as a way to inform the user that something has happened inside your mobile app. Even though overusing vibrations makes bad impressions, sometimes using vibrations in apps such as games makes sense. Here, let’s learn how to create vibrations in react native apps.

Lol, the image is just symbolic.

The Vibration API is used to generate vibrations in react native apps. You can create vibration by simply invoking Vibration.vibrate method. Vibrations can be created in two forms- single occurrence and pattern.

In Android, you must need vibration permission in AndroidManifest.xml file as <uses-permission android:name=”android.permission.VIBRATE”/>. It should be noted that the duration of vibration cannot be controlled in an iOS device.

Following is the complete react native vibration example. Here, I have two buttons, when the first button is pressed the device vibrates once whereas when the second button is pressed the device vibrates in a pattern.

import React from 'react';
import {View, Vibration, Button} from 'react-native';

const VibrationExample = () => {
  const duration = 5000;
  const pattern = [1000, 2000, 1000, 2000];

  return (
    <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}>
      <Button
        onPress={() => Vibration.vibrate(duration)}
        title="Vibrate Once"
      />
      <Button
        onPress={() => Vibration.vibrate(pattern)}
        title="Vibrate in Pattern"
      />
    </View>
  );
};

export default VibrationExample;

It should be noted that this code works only with real devices as you can’t see any effects in a simulator. I hope you liked this react native tutorial.

1 thought on “How to Create Vibrations in React Native”

Leave a Reply

%d bloggers like this: