Explain Codes LogoExplain Codes Logo

Reactjs: How to determine if the application is being viewed on mobile or desktop browser

javascript
responsive-design
hooks
conditional-rendering
Alex KataevbyAlex Kataev·Nov 14, 2024
TLDR

Detect if application is viewed on mobile or desktop in ReactJS by leveraging window.matchMedia. Use this simple snippet:

const isMobile = window.matchMedia("(max-width: 768px)").matches;

Set the isMobile flag to true for screens smaller than 768px — an indication of a mobile device. Tweak the max-width as needed to match your responsive breakpoints. Utilize isMobile to adjust your application's behavior per screen size.

This solution is a quick way to determine what to render. For a thorough understanding of dynamic detection in React, keep reading.

Dynamic rendering with React hooks

Seamless switch with window resize

Improve your React components to adapt in real-time to changes in screen sizes. This is crucial as users can rotate their mobile devices or change the size of their desktop browser window:

import React, { useState, useEffect } from 'react'; // Here's a fun little hook to take the headache out of device detection const useDeviceDetect = () => { // What's smaller than 768 pixels and makes phone calls? Yes, it's a mobile device! const [isMobile, setIsMobile] = useState(window.innerWidth < 768); useEffect(() => { // And now, a magic trick! Watch as we make your screen respond in real-time... const handleResize = () => setIsMobile(window.innerWidth < 768); window.addEventListener('resize', handleResize); // Always clean up after ourselves, folks... return () => window.removeEventListener('resize', handleResize); }, []); return { isMobile }; }; export default useDeviceDetect;

Dynamic adjustments with custom hooks

Our custom React hook, useDeviceDetect, helps handle the dynamic rendering of components based on the device width. It listens for the window's resize event to ensure the UI is continuously updated to match the new window size.

import React from 'react'; import useDeviceDetect from './useDeviceDetect'; // We like our components like we like our coffee...responsive! const MyResponsiveComponent = () => { const { isMobile } = useDeviceDetect(); return ( <div> { /* Bada-bing, bada-boom! We serve different dishes to different devices */ isMobile ? <MobileComponent /> : <DesktopComponent /> } </div> ); }; export default MyResponsiveComponent;

Using tools to power up detection

Media queries using "react-responsive"

For granular control, incorporate the react-responsive library. It facilitates conditional rendering based on media queries just like CSS:

import { useMediaQuery } from 'react-responsive'; const MyComponent = () => { // Do you hear that? It's your screen talking to your media queries! const isTabletOrMobile = useMediaQuery({ query: '(max-width: 1224px)' }); const isPortrait = useMediaQuery({ query: '(orientation: portrait)' }); // Conditional rendering based on the whispers of the media queries }; export default MyComponent;

Enhanced detection with "React Device Detect"

Sometimes, you may need detailed information about the device, not just the screen size. The React Device Detect library provides comprehensive information like OS, browsers, and more:

import { BrowserView, MobileView } from 'react-device-detect'; // We presORT yoUR CAmELS here (devices, we mean devices...) const MyComponent = () => { return ( <> <BrowserView> {/* Don't fear, DesktopComponent is here! */} <DesktopComponent /> </BrowserView> <MobileView> {/* Look! Up in the sky! It's MobileComponent! */} <MobileComponent /> </MobileView> </> ); }; export default MyComponent;

This library offers dedicated components like BrowserView and MobileView for better readability in your code.