ReactJS: How to determine if the application is being viewed on mobile or desktop browser
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
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
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