how to hide/show a React component depending on device browser?

Viewed 356

Looking to hide/show a component in a React/Nextjs/tailwind webapp depending on the device that the user is on (e.g. desktop vs tablet vs mobile) since there are certain keys on the keyboard available for desktop but not on table and mobile (e.g. the tab key). Don't want to do it by screen size since this is a device problem (no tab on keyboard) rather than a screen size problem

Initially I thought about getting device type (code referenced from another stackoverflow Q/A), but this seems to fail when the user is on a device such as an ipad and is using the Desktop version for that browser (e.g. Desktop safari and not mobile safari). Is there a better way to handle this such that it can properly check what device the user is on in order to be able to hide/show the react component?

const getDeviceType = () => {
  const ua = navigator.userAgent;
  if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(ua)) {
    return "tablet";
  }
  if (
    /Mobile|iP(hone|od)|Android|BlackBerry|IEMobile|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(
      ua
    )
  ) {
    return "mobile";
  }
  return "desktop";
};
1 Answers

In JavaScript you can detect browser with JavaScript using window.navigator

Code example according to https://developer.mozilla.org/en-US/docs/Web/API/Window/navigator would be

var sBrowser, sUsrAg = 
navigator.userAgent;

// The order matters here, and this may 
 report false positives for unlisted 
 browsers.

 if (sUsrAg.indexOf("Firefox") > -1) {
sBrowser = "Mozilla Firefox";
// "Mozilla/5.0 (X11; Ubuntu; Linux 
x86_64; rv:61.0) Gecko/20100101 
Firefox/61.0"
}

alert("You are using: " + sBrowser);

But for react there's another package you can use that is npm install react-device-detect

Code example would be

import { browserName, browserVersion } 
from "react-device-detect"
console.log(`${browserName} 
${browserVersion}`);

After detecting browser you just conditionally render whatever you want to show

Related