'ReactJS: How to determine if the application is being viewed on mobile or desktop browser
In ReactJS, is there a way to determine if the website is being viewed on mobile or desktop? Because, depending on which device I would like to render different things.
Thank you
Solution 1:[1]
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;
Solution 2:[2]
You can use React Device Detect Package
This package uses the user-agent
of the browser rather than the screen size.
This can be helpful when wanting to display different things if on desktop vs mobile or certain links based on the device
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
Solution 3:[3]
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
Solution 4:[4]
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>
);
}
});
Solution 5:[5]
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 :-)
Solution 6:[6]
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 />
Solution 7:[7]
Create a Custom Hook and Listen to Resize, load, orientationchange and reload will rerender the component where you have used this hook.
import { useState, useEffect } from 'react';
const useDeviceDetect = () => {
const checkForDevice = () => {
let windowWidth = window.innerWidth;
if (windowWidth < 767.98) {
return true;
} else {
return false;
}
};
const [isMobile, setIsMobile] = useState(checkForDevice());
useEffect(() => {
const handlePageResized = () => {
setIsMobile(checkForDevice);
};
window.addEventListener('resize', handlePageResized);
window.addEventListener('orientationchange', handlePageResized);
window.addEventListener('load', handlePageResized);
window.addEventListener('reload', handlePageResized);
return () => {
window.removeEventListener('resize', handlePageResized);
window.removeEventListener('orientationchange', handlePageResized);
window.removeEventListener('load', handlePageResized);
window.removeEventListener('reload', handlePageResized);
};
}, []);
return {
isMobile,
};
};
export default useDeviceDetect;
Solution 8:[8]
This is not specifc to React but here is my js fonction:
export const isMobile = () => window.matchMedia && window.matchMedia("(max-width: 480px)").matches
Solution 9:[9]
const getNumberDesignRequest = screenWidth => {
let numberDesignRequest = 20
if (screenWidth >= 1280 && screenWidth < 1525) {
numberDesignRequest = 21
}
return numberDesignRequest
}
const ScreenWidth = () => {
const [screenWidth, setScreenWidth] = useState(window.innerWidth)
useLayoutEffect(() => {
const handleResize = () => {
const { innerWidth } = window
setScreenWidth(innerWidth)
}
window.addEventListener('resize', debounce(handleResize, 1000))
return () => window.removeEventListener('resize', handleResize)
}, [])
return screenWidth
}
const FuzzySearch = () => {
const screenWidth = ScreenWidth()
const numberDesignRequest = getNumberDesignRequest(screenWidth)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Raz Luvaton |
Solution 2 | |
Solution 3 | Jay Mayu |
Solution 4 | Anubhav Gupta |
Solution 5 | |
Solution 6 | ZStoneDPM |
Solution 7 | Jayasuriyan |
Solution 8 | Remy Mellet |
Solution 9 |