Nowadays, it's difficult to determine whether a device is mobile or not. Screen size is not a reliable data point, since there are smartphones with viewports greater than 768 px when you turn them horizontally (e.g. iPhone Pro Max or Samsung Galaxy Note).
We'll consider mobile devices, those with multiple touchpoints on the screen (some laptops will be included in this category as well).
We're going to check maxTouchPoints
or msMaxTouchPoints
. If one of these parameters is greater than 1, we'll consider the device (to be) mobile.
Let's define the function in JavaScript:
javascriptlet isMobile = navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0;
Now, we can take use the piece of code in React:
jsximport React, { useEffect, useState } from 'react'; const App = () => { const [isMobile, setIsMobile] = useState(null); useEffect(() => { setIsMobile(navigator.maxTouchPoints > 0 || navigator.msMaxTouchPoints > 0); }, []) return( <div> {isMobile ? 'Mobile device' : 'No mobile device'} </div> ); } export default App;
Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.