To implement a custom hook for handling screen orientation changes in React, you can utilize the window
object and the resize
event to detect changes in screen dimensions. Here's how you can achieve this:
javascriptimport { useEffect, useState } from 'react';
const useScreenOrientation = () => {
const [orientation, setOrientation] = useState(getOrientation());
useEffect(() => {
const handleOrientationChange = () => {
setOrientation(getOrientation());
};
window.addEventListener('resize', handleOrientationChange);
return () => {
window.removeEventListener('resize', handleOrientationChange);
};
}, []);
return orientation;
};
const getOrientation = () => {
if (window.innerHeight > window.innerWidth) {
return 'portrait';
} else {
return 'landscape';
}
};
export default useScreenOrientation;
In this custom hook:
useScreenOrientation
hook that returns the current screen orientation.getOrientation
function.resize
event on the window
object. When the window is resized, the handleOrientationChange
function is called to update the orientation state.getOrientation
function, which checks whether the window height is greater than its width. If so, it returns 'portrait'
; otherwise, it returns 'landscape'
.You can use this custom hook in your components as follows:
javascriptimport React from 'react';
import useScreenOrientation from './useScreenOrientation';
const MyComponent = () => {
const orientation = useScreenOrientation();
return (
<div>
<h1>Screen Orientation: {orientation}</h1>
</div>
);
};
export default MyComponent;
With this setup, your component will automatically update when the screen orientation changes, and it will display the current orientation ('portrait' or 'landscape').