Find the current device orientation like landscape or portrait or landscape and portrait screen detections
Mastering Screen Orientation Detection in ReactJS: A Seamless User Experience
In today's digital age, where smartphones, tablets, and laptops are ubiquitous, creating responsive web applications that adapt to various screen orientations is crucial. Whether it's portrait mode for reading articles or landscape mode for viewing videos, providing a seamless user experience across different screen orientations is essential. In this blog, we'll explore how to detect screen orientation changes in a ReactJS application. import React, { useState, useEffect } from 'react'; const PORTRAIT_MODE = 'portrait'; const LANDSCAPE_MODE = 'landscape'; const ScreenOrientationDetector = () => { const [screenMode, setScreenMode] = useState(null); useEffect(() => { const screenOrientation = () => { if (window.matchMedia("(orientation: portrait)").matches) { screenMode !== PORTRAIT_MODE && setScreenMode(PORTRAIT_MODE); } if (window.matchMedia("(orientation: landscape)").matches) { screenMode !== LANDSCAPE_MODE && setScreenMode(LANDSCAPE_MODE); } }; screenOrientation(); window.addEventListener("orientationchange", screenOrientation); window.addEventListener("resize", screenOrientation); window.addEventListener("change", screenOrientation); return () => { window.removeEventListener("orientationchange", screenOrientation); window.removeEventListener("resize", screenOrientation); window.removeEventListener("change", screenOrientation); }; }, [screenMode]); return ( <div> <p>Screen Mode: {screenMode}</p> </div> ); }; export default ScreenOrientationDetector;
Explanation:
- The
useEffecthook is invoked after every render, and it's responsible for setting up event listeners for orientation changes and window resizing. It also calls thescreenOrientationfunction initially. - Inside the
screenOrientationfunction, we utilizewindow.matchMediato check the current screen orientation. If the orientation matches either portrait or landscape, it updates thescreenModestate accordingly usingsetScreenMode. - The
useEffecthook also includes a cleanup function returned by the hook. This cleanup function removes the event listeners to avoid memory leaks when the component unmounts or when the dependencies change.
Conclusion
In this blog post, we've discussed the importance of detecting screen orientation changes in a ReactJS application. By utilizing React hooks like useEffect and useState, we can efficiently manage screen orientation detection and provide a responsive user experience. Whether your users are browsing in portrait or landscape mode, understanding and adapting to their preferred orientation is key to creating engaging and accessible web applications.
Comments
Post a Comment