React detect device type

Problem

You work on your awesome React Project. And you need to create conditional code detecting the device type your project is running on.

If you need to know what kind of device your react app is running on have a look at this packages :https://www.npmjs.com/package/react-device-detect.

Solution: React detect device type

1. Have a look at this npm package :https://www.npmjs.com/package/react-device-detect. Install it with npm install react-device-detect –save.

2. Import the required functionality e.g.

import { browserName, isSmartTV, isWearable } from 'react-device-detect';

3. Write conditional code
{ (isSmartTV && your code here) }

Explanation

react-device-detect is a small library that determines the type of device your code is running on for you.

From the previous example:

  • browserName returns the name of the Browser used.
  • isSmartTV tells you if the device is a SmartTV.
  • isWearable tells you if the device is a Wearable, e.g. a iWatch

Based on these information you can make programmatic decision which path the code should follow and which components to use.

Background

To create DRY, clean and simple code you wanna keep components as small and easy as possible.

That can mean having multiple components to render the same element for different device type. And responsive design goes only so far.

But you need to somehow determine which component to load and display.

Or you need to load different components e.g. for an iWatch or TV to handle different abilities of inputting information.

By having a reliable way to detect the device type your react code is running on, you can make the decision required. You can rest assured that you have reliable code to stand to base your work on. And stand on the shoulder of giants.

Let me know if it helped. And if you have other tips to detect the device type in react.

Best,

Frank

Leave a Reply