Kinda Code
Home/React/How to determine mobile or desktop in React

How to determine mobile or desktop in React

Last updated: March 03, 2023

An easy solution to determine whether your React app is rendering on a mobile device or a computer is to use a library called react-device-detect.

A Complete Example

Installation:

npm install react-device-detect --save

The code:

import React from "react";
import { isMobile } from "react-device-detect";

function App() {
  return (
    <div style={styles.container}>
      {isMobile ? <h2>Mobile</h2> : <h2>Desktop</h2>}
    </div>
  );
}

// just a little styling
const styles = {
  container: {
    display: 'flex',
    justifyContent: 'center',
    paddingTop: '15px'
  }
}

export default App;

Check it out with the Chrome developer tool:

for the sake of brevity and ease of understanding, any unnecessary verbosity has been removed from the code.

If you want to trigger an update on window resizes instead of manually refreshing the browser as shown in the video above, then see this article: React + TypeScript: Re-render a Component on Window Resize (This is not required because, in practice, normal users won’t turn on Chrome’s dev tools and do as we do).

Conclusion

You’ve learned a simple and quick technique to detect mobile or desktop in React. If you’d like to explore more new and exciting stuff about modern front-end development, take a look at the following articles:

You can also check our React category page and React Native category page for the latest tutorials and examples.

Related Articles