How to Create Vibrations in React Native

Last Updated on December 15, 2020.

Vibrations can be used as a way to inform the user that something has happened inside your mobile app. Even though overusing of vibrations make bad impressions, sometimes using vibrations in apps such as games make sense. Here, let’s ‘earn 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.

Class Component

import React, { Component } from 'react';
import { View, Vibration } from 'react-native';
import Button from '../../components/Button';

export default class VibrationExample extends Component {
  constructor(props) {
    super(props);
    this.state = {
        duration: 5000,
        pattern: [1000, 2000, 1000, 2000]

    };
  }


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

Function Component

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

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)} text="Vibrate Once" />
      <Button
        onPress={() => Vibration.vibrate(pattern)}
        text="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: