0
0
React Nativemobile~5 mins

Device info and haptics in React Native

Choose your learning style9 modes available
Introduction

Knowing device info helps your app adjust to different phones. Haptics give users a gentle vibration to feel feedback.

Show device model or OS version in app settings
Make buttons vibrate slightly when tapped
Adjust layout based on screen size or orientation
Give feedback when a user completes an action
Detect if device supports vibration before using it
Syntax
React Native
import { Platform, Dimensions, Vibration } from 'react-native';

// Get device info
const os = Platform.OS; // 'ios' or 'android'
const version = Platform.Version; // OS version number
const { width, height } = Dimensions.get('window');

// Use haptics
Vibration.vibrate(100); // vibrate for 100 milliseconds

Platform tells you the OS type and version.

Dimensions gives screen size to help layout.

Vibration triggers device vibration for feedback.

Examples
This prints the device operating system, like 'ios' or 'android'.
React Native
const os = Platform.OS;
console.log(os);
This gets the screen width and height in pixels.
React Native
const { width, height } = Dimensions.get('window');
console.log(`Width: ${width}, Height: ${height}`);
This makes the device vibrate for 200 milliseconds.
React Native
Vibration.vibrate(200);
Sample App

This app shows the device OS, version, and screen size. Pressing the button makes the device vibrate shortly.

React Native
import React from 'react';
import { View, Text, Button, Platform, Dimensions, Vibration, StyleSheet } from 'react-native';

export default function DeviceInfoHaptics() {
  const os = Platform.OS;
  const version = Platform.Version;
  const { width, height } = Dimensions.get('window');

  const handleVibrate = () => {
    Vibration.vibrate(150);
  };

  return (
    <View style={styles.container} accessible={true} accessibilityLabel="Device info and haptics screen">
      <Text style={styles.text}>OS: {os}</Text>
      <Text style={styles.text}>Version: {version}</Text>
      <Text style={styles.text}>Screen: {width} x {height}</Text>
      <Button title="Vibrate Device" onPress={handleVibrate} accessibilityLabel="Button to vibrate device" />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
    backgroundColor: '#f0f0f0'
  },
  text: {
    fontSize: 18,
    marginBottom: 10
  }
});
OutputSuccess
Important Notes

Not all devices support vibration; test before using.

Use Platform.OS to write OS-specific code.

Screen size helps make your app look good on all devices.

Summary

Use Platform to get OS info.

Use Dimensions to get screen size.

Use Vibration to give tactile feedback.