Skip to content

useDeviceMotion

See: device motion.

Demo

INFO

The component uses useDeviceMotion hook to show device motion details.

Loading demo…
Show source code
tsx
import { Fragment } from "react";
import { useDeviceMotion } from "../../../.."

export const UseDeviceMotion = () => {
	const data = useDeviceMotion();

	return <div style={{ textAlign: "center" }}>
		{
			Object.keys(data).map(key => {
				const value = data[key as keyof typeof data];
				return value !== null && typeof value === "object" && Reflect.get(value, "x")
					? <Fragment key={key}>
						<p>{key}:</p>
						<ul>
							<li>x: {Reflect.get(data[key as keyof typeof data] as object, "x")}</li>
							<li>y: {Reflect.get(data[key as keyof typeof data] as object, "y")}</li>
							<li>z: {Reflect.get(data[key as keyof typeof data] as object, "z")}</li>
						</ul>
					</Fragment>
					: value !== null && typeof value === "object" && Reflect.get(value, "alpha")
						? <Fragment key={key}>
							<p>{key}:</p>
							<ul>
								<li>alpha: {Reflect.get(data[key as keyof typeof data] as object, "alpha")}</li>
								<li>beta: {Reflect.get(data[key as keyof typeof data] as object, "beta")}</li>
								<li>gamma: {Reflect.get(data[key as keyof typeof data] as object, "gamma")}</li>
							</ul>
						</Fragment>
						: <p key={key}>{key}: {value !== null ? value.toString(): ""}</p>
			})
		}
	</div>
}

Types

UseDeviceMotionResult

Reactive snapshot of the device motion sensor data, returned by useDeviceMotion. Values are updated whenever the browser fires devicemotion events.

PropertyTypeRequiredDescription
isSupportedbooleantrue when the DeviceMotionEvent API is supported and permission has been granted.
accelerationDeviceMotionEventAcceleration \| nullAcceleration of the device along x, y, and z axes in m/s², excluding the effect of gravity. null when not available or not supported.
accelerationIncludingGravityDeviceMotionEventAcceleration \| nullAcceleration of the device along x, y, and z axes in m/s², including the contribution of gravity (approximately 9.8 m/s² on the z-axis at rest). null when not available or not supported.
rotationRateDeviceMotionEventRotationRate \| nullRate of rotation around each axis in degrees per second (alpha, beta, gamma). null when not available or not supported.
intervalnumber \| nullInterval in milliseconds at which data is obtained from the hardware sensor. null when not available.

Released under the MIT License.