How to adjust a video player to device orientation
This example demonstrates how to adjust a video player to device orientation using the useDeviceOrientation
hook.
tsx
import { useDeviceOrientation } from "./useDeviceOrientation";
export default function App() {
const orientation = useDeviceOrientation();
return (
<video
src="https://www.w3schools.com/html/mov_bbb.mp4"
controls
style={{
width: "100%",
maxHeight: orientation.type.includes("landscape") ? "100vh" : "auto",
}}
/>
);
}
typescript
import { useSyncExternalStore } from "react";
const orientationSubscribe = (cb: () => void) => {
window.addEventListener("orientationchange", cb);
return () => window.removeEventListener("orientationchange", cb);
};
const getOrientation = () => {
const { type, angle } = window.screen.orientation;
return JSON.stringify({ type, angle });
};
export const useDeviceOrientation = () =>
JSON.parse(useSyncExternalStore(orientationSubscribe, getOrientation));