Examples
Practical examples for @mhpdev/react-native-haptics, taken from the example project.
Example application
The example project in the repository renders a button for every impact style, notification type, selection, and — on Android — every androidHaptics effect.
Feedback on button press
import React from 'react';
import Haptics from '@mhpdev/react-native-haptics';
import {SafeAreaView, StyleSheet, Text, TouchableOpacity} from 'react-native';
const App: React.FC = () => {
const onImpactPress = () => {
Haptics.impact('heavy');
};
return (
<SafeAreaView style={styles.container}>
<TouchableOpacity style={styles.button} onPress={onImpactPress}>
<Text style={styles.buttonText}>Trigger Heavy Impact</Text>
</TouchableOpacity>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
button: {
padding: 12.5,
borderRadius: 5,
backgroundColor: 'skyblue',
},
buttonText: {
fontSize: 22,
fontWeight: '600',
},
});Result feedback after an action
async function save() {
try {
await persist();
Haptics.notification('success');
} catch {
Haptics.notification('error');
}
}Cross-platform code with Android-only effects
androidHaptics is a no-op on iOS, so it can be called unconditionally; the example project still renders those buttons only on Android:
import {Platform} from 'react-native';
// Rendering the Android-only section of the example app
{
Platform.OS !== 'android' ? null : (
<HapticButton
title="Confirm"
onPress={() => Haptics.androidHaptics('confirm')}
/>
);
}Selection feedback
// e.g. in a segmented control change handler
onValueChange={() => Haptics.selection()}For measured timings of each effect, see Benchmarks.