how to get orientation type and lock orientation in ReactJS? The Screen Orientation API doesn't work with ReactJS or I just don't know how to install and use it. Please guide me to do the above. Thanks.
Since this answer still receives upvotes in 2025, here's an up-to-date suggestion:
In most cases, you should use Screen Orientation API, which is reasonably well supported by now.
You might want to implement your useOrientation() hook enclosing respective logic (for consistent use across your entire app) and serving as an adaptor to screen.orientation as follows:
import { useEffect, useState } from 'react';
export const useOrientation = () => {
const [orientationType, setOrientationType] = useState();
useEffect(() => {
const trackOrientation = (orientationChangeEvent) =>
setOrientationType(
orientationChangeEvent?.target?.type ?? screen.orientation.type
);
trackOrientation();
screen.orientation.addEventListener('change', trackOrientation);
return () =>
screen.orientation.removeEventListener('change', trackOrientation);
}, []);
return {
getOrientationType: () => orientationType,
lockOrientation: () => screen.orientation.lock(orientationType),
unlockOrientation: () => screen.orientation.unlock(),
};
};
Pay attention, though, that screen.orientation.lock() might still have limited support.
On the other hand, if you, for whatever reason, prefer to keep track of window resize and update your screen orientation state based on that, I'd suggest ditching resize event listener (proposed by me back in early 2020) for Resize Observer API for a whole bunch of reasons (including performance).
In that case, you may build your useResizeObserver() hook as simple as that:
import { useEffect } from 'react';
export const useResizeObserver = (resizeCallback, target = document.body) => {
const resizeObserver = new ResizeObserver(resizeCallback);
useEffect(() => {
resizeObserver.observe(target);
return () => resizeObserver.disconnect();
}, []);
};
With that you may pass the callback of your choice (which might set orientation state within the required component) invoked upon document.body resize:
export const MyComponent = () => {
const [screenOrientationType, setScreenOrientationType] = useState(screen.orientation.type);
const handleScreenResize = () => setScreenOrientationType(screen.orientation.type);
useResizeObserver(handleScreenResize)
..
}
Due to Resize Observer batching resize events internally, you shouldn't likely bother about debouncing suggested in the previous edit of this answer.
And, of course, if you're reluctant to build and support your own solution, you may likely opt-in for a library that does the job for you (e.g. react-use).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With