Simple Vibration
In this approach, a straightforward method will be implemented to facilitate the creation of vibrations. The process involves utilizing a start button and a stop button. By pressing the “Vibrate” button, it will initiate the vibration sequence, whereas activating the “Stop Vibration” button will halt the ongoing vibration.
Example:
Javascript
//App.js import React, { useState } from 'react' ; import { View,TouchableOpacity,Text,Vibration,StyleSheet } from 'react-native' ; const App = () => { const [vibrating, setVibrating] = useState( false ); const startVibration = () => { setVibrating( true ); Vibration.vibrate(3000); }; const stopVibration = () => { setVibrating( false ); Vibration.cancel(); }; return ( <View style={styles.container}> <Text style={styles.heading}> w3wiki! </Text> <TouchableOpacity style={[styles.button, vibrating && styles.disabledButton]} onPress={startVibration} disabled={vibrating} > <Text style={styles.buttonText}> Start Vibration </Text> </TouchableOpacity> <TouchableOpacity style={[styles.button, !vibrating && styles.disabledButton]} onPress={stopVibration} disabled={!vibrating} > <Text style={styles.buttonText}> Stop Vibration </Text> </TouchableOpacity> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center' , alignItems: 'center' , backgroundColor: '#f5f5f5' , }, heading: { color: 'green' , fontSize: 30, fontWeight: 'bold' , marginBottom: 20, }, button: { backgroundColor: '#3498db' , paddingVertical: 15, paddingHorizontal: 30, borderRadius: 5, marginVertical: 10, }, disabledButton: { backgroundColor: '#bdc3c7' , }, buttonText: { color: 'white' , fontSize: 16, fontWeight: 'bold' , }, }); export default App; |
To Run Native application use the following command:
npx expo start
- To run on Android:
npx react-native run-android
- To run on Ios:
npx react-native run-ios
Output:
How to Add Start Stop Device Vibration in React Native?
Vibration is a very useful feature in mobile applications to provide feedback or alerts. In this article, we will create a custom button to start and stop vibrations using React Native.