In this tutorial, we will create a React component that detects if a user is accessing the app from a mobile device.
Prerequisites:
- Basic understanding of React.
- Create React App or any React setup.
Step 1: Create a React App
If you don’t have a React app yet, you can create one using Create React App
:
npx create-react-app detect-mobile
cd detect-mobile
npm start
Step 2: Install react-device-detect
Package
To easily detect devices, we’ll use a package called react-device-detect
. It provides simple utilities to detect the type of device.
Install the package using npm or yarn:
npm install react-device-detect
Step 3: Create the Mobile Detection Component
Now, create a new component DetectMobile.js
to detect if the user is on a mobile device:
// src/DetectMobile.js
import React from 'react';
import { isMobile } from 'react-device-detect';
const DetectMobile = () => {
return (
<div>
{isMobile ? (
<h1>You are using a mobile device</h1>
) : (
<h1>You are using a desktop or tablet</h1>
)}
</div>
);
};
export default DetectMobile;
Step 4: Use the Component
Now, use the DetectMobile
component inside your App.js
:
// src/App.js
import React from 'react';
import './App.css';
import DetectMobile from './DetectMobile';
function App() {
return (
<div className="App">
<header className="App-header">
<DetectMobile />
</header>
</div>
);
}
export default App;
Step 5: Test the App
Start your app:
npm start
Open the app in your browser. If you open it on a desktop browser, it should display: “You are using a desktop or tablet”.
If you open it on a mobile device, it should display: “You are using a mobile device”.
Step 6 (Optional): Customizing Device Detection
You can also detect other device types such as tablets or iOS devices with the same react-device-detect
package:
import { isMobile, isTablet, isIOS } from 'react-device-detect';
if (isMobile) {
console.log("Mobile device detected");
}
if (isTablet) {
console.log("Tablet detected");
}
if (isIOS) {
console.log("iOS device detected");
}
Conclusion
In this tutorial, you learned how to detect mobile devices in a React app using the react-device-detect
package. This is a useful technique to adjust your UI based on the type of device a user is accessing your app from.