← Back
react webapi

Device orientation API

I didn't know that device orientation API exist. I was thrilled when I discovered, but as David pointed out to me, it's new and lacks broswer support.

Anyway, this was my attempt to use it in react:

src/hooks/useDeviceOrientation.tsx:

import { useState, useEffect, useCallback } from "react";

const getOrientation = () => window.screen.orientation.type;

const useScreenOrientation = () => {
const [orientation, setOrientation] = useState(getOrientation());

const updateOrientation = useCallback(() => {
setOrientation(getOrientation());
}, [setOrientation]);

useEffect(() => {
window.addEventListener("orientationchange", updateOrientation);
return () => {
window.removeEventListener("orientationchange", updateOrientation);
};
}, []);

const isPortrait =
orientation === "portrait-primary" || orientation === "portrait-secondary";
const isLandscape = !isPortrait;

return { orientation, isPortrait, isLandscape };
};

export default useScreenOrientation;

Since I need just to know if it's portrait or landscape, I've finally decided not to use it, so I made a simple version that just compares window width and height:

import { useState, useEffect, useCallback } from "react";

type Orientation = "portrait" | "landscape";

const getOrientation = (): Orientation => {
return window.innerWidth > window.innerHeight ? "landscape" : "portrait";
};

/**
* The ideal would be using window.screen.orientation API but is not well supported or broken
*/

const useScreenOrientation = () => {
const [orientation, setOrientation] = useState<Orientation>(getOrientation());

const updateOrientation = useCallback(() => {
setOrientation(getOrientation());
}, [setOrientation]);

useEffect(() => {
window.addEventListener("resize", updateOrientation);
return () => {
window.removeEventListener("resize", updateOrientation);
};
}, []);

const isPortrait = orientation === "portrait";
const isLandscape = !isPortrait;

return { orientation, isPortrait, isLandscape };
};

export default useScreenOrientation;