A React hook package that allows reading iPad device orientation accurately (yaw, pitch, roll).
npm install ipad-device-orientationipad-device-orientation is a React hook package that allows reading iPad device orientation accurately (yaw, pitch, roll).
OrientationPanel.
bash
npm install ipad-device-orientation
`
or using yarn:
`bash
yarn add ipad-device-orientation
`
---
Hook Usage
`tsx
import React from 'react';
import { useDeviceOrientation } from 'ipad-device-orientation';
const MyComponent = () => {
const { yaw, pitch, roll, resetYaw, permissionGranted, requestPermission } = useDeviceOrientation();
return (
{!permissionGranted ? (
) : (
Yaw: {yaw.toFixed(1)}°
Pitch: {pitch.toFixed(1)}°
Roll: {roll.toFixed(1)}°
)}
);
};
`
Notes on values:
- Pitch: horizon = 0°, looking down = -90°, looking up = 90°.
- Roll: horizontal tilt relative to horizon. Small tilts give accurate roll.
- Yaw: based on device alpha with optional offset. Reflects compass heading.
---
Full Example
A sample is available at the github page of this project that illustrates how to wire the hook in an React application
---
Using DeviceOrientationProvider (React Context)
If your app has multiple components that need device orientation, or if you’re using a router-based application, calling the hook separately in each component may not be ideal. Instead, it can be more convenient to use a context provider. This approach ensures that orientation is tracked once and the values are shared across all components, simplifying your code and preventing multiple event listeners.
Example:
`typescript
// App.tsx
import React from "react";
import { DeviceOrientationProvider } from "ipad-device-orientation";
import { OrientationPanel } from "./components/OrientationPanel";
import { AnotherComponent } from "./components/AnotherComponent";
// Wrapp with DeviceOrientationProvider any component that may require orientation
const App: React.FC = () => {
return (
);
};
export default App;
`
Consuming the Context
`typescript
import React from "react";
import { useDeviceOrientationContext } from "ipad-device-orientation";
export const AnotherComponent: React.FC = () => {
const { yaw, pitch, roll, resetYaw, permissionGranted, requestPermission } =
useDeviceOrientationContext();
return (
Device Orientation:
Yaw: {yaw.toFixed(1)}°
Pitch: {pitch.toFixed(1)}°
Roll: {roll.toFixed(1)}°
{!permissionGranted && (
)}
);
};
``