PASSWORD RESET

Your destination for complete Tech news

How to detect a mobile device in React JS?

2.65K 0
< 1 min read

To detect whether a user is accessing your React application from a mobile device, you can use the window.matchMedia() method with a media query that targets mobile devices. Here’s how you can do it:

import React, { useState, useEffect } from 'react';

function MobileDeviceDetector() {
  const [isMobile, setIsMobile] = useState(false);

  useEffect(() => {
    const mobileMediaQuery = window.matchMedia('(max-width: 767px)'); // Adjust the breakpoint as needed

    const handleMobileChange = (event) => {
      setIsMobile(event.matches);
    };

    mobileMediaQuery.addEventListener('change', handleMobileChange);
    setIsMobile(mobileMediaQuery.matches);

    return () => {
      mobileMediaQuery.removeEventListener('change', handleMobileChange);
    };
  }, []);

  return (
    <div>
      {isMobile ? <p>This is a mobile device.</p> : <p>This is not a mobile device.</p>}
    </div>
  );
}

export default MobileDeviceDetector;

In this example, the MobileDeviceDetector component uses the useState and useEffect hooks to manage the state of whether the user is on a mobile device. The useEffect hook sets up a listener for changes in the media query (max-width: 767px) (you can adjust the breakpoint as needed to match your definition of mobile devices). When the media query matches the condition, the handleMobileChange function updates the state.

The component then conditionally renders a message indicating whether the user is on a mobile device or not.

Keep in mind that this approach is based on screen width and may not be foolproof for all mobile devices. Additionally, there are libraries like react-device-detect that offer a more comprehensive way to detect various device types and capabilities.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.