Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you detect if device is mobile or desktop react JS?

import { isMobile } from "react-device-detect"; const DetectDevice = () => ( Device is : {isMobile ? "Mobile" : "Desktop"} ); export default DetectDevice; You can also control the rendering as per the device detection.

How do you check which browser is being used in react JS?

Check browser name For example, to get the browser name and version, we will import browserName and browserVersion from the library. import { browserName, browserVersion } from "react-device-detect"; If we log these two values to the console, we will see the following.

How do I view my React app on my phone?

Simply pull up your device's browser and type in the IPv4 Address you copied down earlier followed by a colon and then the port number. The format should look something like the following: 555.55. 55.555:1234 once you hit enter, you should see your React App live on your mobile device!


Simple solution using react hooks

const [width, setWidth] = useState<number>(window.innerWidth);

function handleWindowSizeChange() {
    setWidth(window.innerWidth);
}
useEffect(() => {
    window.addEventListener('resize', handleWindowSizeChange);
    return () => {
        window.removeEventListener('resize', handleWindowSizeChange);
    }
}, []);

const isMobile = width <= 768;

You can use React Device Detect Package

Installation

To install, you can use npm or yarn:

# For NPM:
npm install react-device-detect --save

# For Yarn
yarn add react-device-detect

Usage

Example:

import {BrowserView, MobileView} from 'react-device-detect';

const MyComponent = () => {
    return (
        <>
            <BrowserView>
                <h1>This is rendered only in browser</h1>
            </BrowserView>
            <MobileView>
                <h1>This is rendered only on mobile</h1>
            </MobileView>
        </>
    );
};

if you don't need a view, you can use isMobile for conditional rendering

import {isMobile} from 'react-device-detect';

const MyComponent = () => {
    if(isMobile) {
        return (
            <div> This content is available only on mobile</div>
        )
    }
    return (
        <div> content... </div>
    );
};

Taken from React Device Detect README with a little modification


What you are looking for is called react-responsive. You can find it here

Here is how to use quick guide from their repo:

var MediaQuery = require('react-responsive');

var A = React.createClass({
  render: function(){
    return (
      <div>
        <div>Device Test!</div>

        <MediaQuery minDeviceWidth={1224}>
          <div>You are a desktop or laptop</div>
        </MediaQuery>
        <MediaQuery maxDeviceWidth={1224}>
          <div>You are a tablet or mobile phone</div>
        </MediaQuery>

        <MediaQuery orientation='portrait'>
          <div>You are portrait</div>
        </MediaQuery>
        <MediaQuery orientation='landscape'>
          <div>You are landscape</div>
        </MediaQuery>

        <MediaQuery minResolution='2dppx'>
          <div>You are retina</div>
        </MediaQuery>
      </div>
    );
  }
});

I further enhanced Volobot's answer. I'd created a hook as below and it works like charm :)

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

const useCheckMobileScreen = () => {
    const [width, setWidth] = useState(window.innerWidth);
    const handleWindowSizeChange = () => {
            setWidth(window.innerWidth);
    }

    useEffect(() => {
        window.addEventListener('resize', handleWindowSizeChange);
        return () => {
            window.removeEventListener('resize', handleWindowSizeChange);
        }
    }, []);

    return (width <= 768);
}

export default useCheckMobileScreen

Why to complicate things when you can use one line of vanilla javascript code?

Use window.screen object to get width of current screen. For example window.screen.width will return value of current width of client in pixels.

Use it inside if (window.screen.width >= 1280) { /* conditional statements */ }

I hope that it helps. Thank you :-)


I used this method for React and it works great in 2020. Thanks @Anubahav Gupta

npm install react-responsive --save

Then create component:

import React, { Fragment, Component } from 'react';
import MediaQuery from 'react-responsive';

class MyMediaQuery extends Component {
    render() {
        return (
            <Fragment>
                <div>Device Test!</div>

                <MediaQuery minDeviceWidth={1224}>
                    <div>You are a desktop or laptop</div>
                </MediaQuery>
                <MediaQuery maxDeviceWidth={1224}>
                    <div>You are a tablet or mobile phone</div>
                </MediaQuery>

                <MediaQuery orientation='portrait'>
                    <div>You are portrait</div>
                </MediaQuery>
                <MediaQuery orientation='landscape'>
                    <div>You are landscape</div>
                </MediaQuery>

                <MediaQuery minResolution='2dppx'>
                    <div>You are retina</div>
                </MediaQuery>
            </Fragment>
        );
    }
}

export default MyMediaQuery;

It works as-is on any page loaded but can also be imported into another file with:

import MyMediaQuery from '.newFileName';

Then used anywhere as:

<MyMediaQuery />