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); } }, []);let isMobile: boolean = (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 Yarnyarn 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> ); }});