Giter Club home page Giter Club logo

react-device-detect's Introduction

react-device-detect

npm

Detect device, and render view according to the detected device type.

Installation

To install, you can use npm or yarn:

npm install react-device-detect --save

or

yarn add react-device-detect

When to use this library

This library uses a technique called user agent sniffing to detect device information. That means it works by examining the User Agent string given by a browser and comparing it to a list of browser and device names it knows about. This technique works, but has drawbacks and may or may not be the right approach, depending on what you're trying to achieve. If you need to detect a specific browser type (e.g. Chrome, Safari, Internet Explorer) or specific category of device (e.g. all iPods), this library can do that. If you just want your React app to behave differently or look different on mobiles in general, CSS @media queries and matchMedia are probably what you want. There are many libraries that can help with using @media queries and matchMedia in React projects, such as react-responsive and @react-hook/media-query.

API

Usage

Example:

import { BrowserView, MobileView, isBrowser, isMobile } from 'react-device-detect';
<BrowserView>
  <h1>This is rendered only in browser</h1>
</BrowserView>
<MobileView>
  <h1>This is rendered only on mobile</h1>
</MobileView>

if you don't need a view, you can use isMobile for conditional rendering

import {isMobile} from 'react-device-detect';

function App() {
  renderContent = () => {
    if (isMobile) {
      return <div> This content is available only on mobile</div>
    }
    return <div> ...content </div>
  }

  render() {
    return this.renderContent();
  }
}

If you want to leave a message to a specific browser (e.g IE), you can use isIE selector

import { isIE } from 'react-device-detect';

function App() {
  render() {
    if (isIE) return <div> IE is not supported. Download Chrome/Opera/Firefox </div>
    return (
      <div>...content</div>
    )
  }
}

If you want to render a view on a specific device and with a specific condition:

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

function App() {
  render() {
    return (
      <CustomView condition={browserName === "Chrome"}>
        <div>...content</div>
      </CustomView>
    )
  }
}

Style the view

You can style a view component by passing class to the className prop

<BrowserView className="custom-class">
  <p>View content</p>
</BrowserView>

or you can pass inline styles to style prop

const styles = {
  background: 'red',
  fontSize: '24px',
  lineHeight: '2',
};
<BrowserView style={styles}>
  <p>View content</p>
</BrowserView>

Testing

import * as rdd from 'react-device-detect';

rdd.isMobile = true;

// use in tests

License

MIT

react-device-detect's People

Contributors

aelghoneimy avatar agmm avatar alexdrimbe avatar askielboe avatar brandoncc avatar danbtl avatar dependabot[bot] avatar devpolo avatar duskload avatar ewolfe avatar ghesericsu avatar gpoole avatar johnphamous avatar jtemplej avatar kidunot89 avatar liamuk avatar moretti avatar niraj-patel avatar pietrobs avatar scriptex avatar sethitushar avatar shaman123 avatar vasilevich avatar vikaspaldev avatar vsfarooqkhan avatar vxvomar avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-device-detect's Issues

Issue on IE

I am getting includes is not a function on IE due to this module. How can I use CommonJS version of it or atleast make it compatible to IE? I am using NextJS v8.1.0 and react-device-detect v1.6.2.

Crawlers vs. browser

Hi, I currently have text animations on my website (showing only when the user scrolls to the element). However, if the content is being accessed by a crawler, I'd like to disable these animations for SEO purposes. I'm not sure if that is possible with this library and whether using isBrowser is enough? Any advice?

Is there any way how to push user agent to mobile list ?

I am using Apache Cordova (in short my custom web browser) with user agent (User-Agent: "this is my mobile app") and problem is that import {isMobile} from 'react-device-detect' returns false for my app (it`s running on android).

Is there any way how to push my UserAgent into library list? It should return true because its running on adroid - but with unknown user agent... :-)

Any tips?

In worst case I can use if (isMobile || getUA() === this is my mobile app)...

Thanks

Doesn't Update UserAgent when device change without reload - testing with Google Device Toolbar

Hi! I love your proyect, it's really useful and i grateful.

I use Google Device Toolbar when i need to test a responsive web page, so this tool change UA data in the air, and doesn't reload the web page when i change device.

In this context (and thinking about using "react-device-detect" as a way to detect when a page is resized) i need a way to update UA data of "react-device-detect", without reload page.

In-App Safari

Is there a way to differentiate MobileSafari and In-App Mobile Safari?

While they are supposed to be the same browser, In-App Mobile Safari currently doesn't support WebRTC so I'm needing to re-direct users to use the actual Mobile Safari app.

typescript support

there is not fully support for typescript. for example isChrome, browserVersion etc.

Working with screen resize

I understand the package works and detect the screen when the page is loading but is there a way to also make the detection upon screen resize like when you use chrome inspect to change screen responsiveness. I have been trying to fix this async but don't seems to get maybe a little help would do

typescript support

I've just installed this app, and put next code into the test component

<BrowserView>
     <h1> This is rendered only in browser </h1>
</BrowserView>
<MobileView>
     <h1> This is rendered only on mobile </h1>
</MobileView>

As result I have typescript compilation error:

JSX element type 'BrowserView' is not a constructor function for JSX elements.
Type 'BrowserView' is missing the following properties from type 'ElementClass': context, setState, forceUpdate, props, and 2 more. TS2605

I've tried to install @types/react-device-detect but there is no package found in npm repo

Do you have DesktopView ?

I think you need to add Desktop View.
But for now, do you have any idea to handle on desktop view ?
because when i use BrowserView then in MobileView and tablet TabletView doesnt rendered.

how to trigger isMobile based on viewport size?

I would like to cypress to test my views, it can set viewport size easily and its supposed to be able to set useragent but dosent seem to really work. the viewport size is however changed, can I trigger ismobile to be true based on viewport size?

Typescript support

Module '"react-device-detect"' has no exported member 'deviceDetect'. I need this function exported for typescript.

isIE still show false

I see there is a close issue about detection with IE and there was an update for that, But I'm not sure if there is something more I need. I have the same behavior with IE11. String is showing IE, but the Boolean display false.
This is the version I have "react-device-detect": "^1.4.5"

Samsung Note 3 (phone) and Lenovo Idea Tab3 - 7inch tablet not properly detected

Hi!
Devices Samsung Note 3 (phone) and Lenovo Idea Tab3 - 7inch tablet are not properly identified on different web browsers :
Android Phone:
<Opera (Mini)> Samsung Note 3 was as expected.
Samsung Note 3 was not as expected. it was not detected as a phone.

Android Tablet:
<Chrome (default)>Lenovo Idea Tab3 - 7inch was not as expected. it was detected as a phone.
Lenovo Idea Tab3 - 7inch was as expected. it was not detected as a phone.
<Opera (Normal)>Lenovo Idea Tab3 - 7inch was not as expected. it was detected as a phone.

If needed i can provide additional logs.
Is there any chance to improve this?
Thanks in advance!

isBrowser is duplicated in index.d.ts

isBrowser is declared two times in typecsript interface
So my compiler is unable to build:
Cannot redeclare block-scoped variable isBrowser

Thank you

How can I use this module for server side rendering?

Hi
Thanks for your module.
This is a small and useful module for the React frontend.
But I can't use this module for server-side rendering.
I think if we can use this module for server-side rendering, this module will be more useful and grateful.
we can analyze request user agent string on the server-side.
I think internal functions will be exported to analyze user agent in this module.
what about your thoughts?
Or can I use this module for server-side rendering now?

problem getting cypress tests to trigger isMobile

Hello, Im not sure if this is a issue with react-device-detect, cypress, or my own fault, but I have this line in my cypress spec at the very top,

Cypress.config('user-agent', 'mobile')

it does not trigger isMobile when I run cypress. I was able to get cypress to trigger isMobile with a cypress.json config file at root of project, with contents of

{
"chromeWebSecurity": false,
"baseUrl": "http://localhost:3000",
"userAgent": "Mozilla/5.0 (Linux; Android 6.0.1; SM-G532G Build/MMB29T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.83 Mobile Safari/537.36"
}

but doing it like this is lame because it makes ALL cypress tests run as mobile, when I really want to be able to do it in each test file like the above.. ty in advance!

withOrientationChange

I would suggest to add ...this.props to the WrappedComponent used in withOrientationChange.js or at least add {props.children} as content.

Add a changelog or release notes

As a developer I want to be able to understand what was changed with new releases available through npm so that I can understand what has changed and whether I need to update. It is also hlpful to understand what kinds of breaking changes may have been introduced.

This can be achieved through either tagged releases or a changelog.

Gatsbyjs: "navigator" is not available during server side rendering

Hi,
This library was working with gatsbyjs (1.9.10) until the last version (1.11.11). I am getting now this error:

failed Building static HTML for pages - 5.562s
ERROR #95312
"navigator" is not available during server side rendering.
See our docs page for more info on this error: https://gatsby.dev/debug-html

416 |
417 | var getIOS13 = function getIOS13() {

418 | return (/iPad|iPhone|iPod/.test(navigator.platform) || navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1) && !window.MSStream;
| ^
419 | };
420 |
421 | var getIPad13 = function getIPad13() {

WebpackError: ReferenceError: navigator is not defined

  • main.js:418 getIOS13
    node_modules/react-device-detect/main.js:418:1

  • main.js:507 Object../node_modules/react-device-detect/main.js
    node_modules/react-device-detect/main.js:507:1

Brave is detected as Chrome

Hi ,
There's no way to distinguish Chrome from Brave, both return same browser name.
Saw some articles about finger printing brave , so it hides on chrome name.
Is there a way to see the difference ?

Jest unit testing mocking isMobile

Hello, I developed an React application using the this package.
While writing the test code but my test didnt coverage the code because isMobile = false. How do I mock isMobile.

Screen Shot 2020-02-25 at 15 57 26

my test code

describe('<Header/>', () => {
  it('renders without crashing.', () => {
    
    const wrapper = mount(
      <MemoryRouter>
          <Header />
      </MemoryRouter>,
    );
    expect(wrapper.find(Header)).toHaveLength(1);
  });
});

Detect mac

Hi,
I was checking the document, but nowhere mentioned about detecting the Mac.
Do you support this feature?

Readme

From Readme.md

if (isMobile) {
        return <div> This content is unavailable on mobile</div>
}

isIE = false on IE11

It appears that on IE11 the variable isIE is set to false.
I tried this page on Chrome and Mobile and the respective variables changed accordingly, but not for IE11.

Am I doing something wrong?

Thanks in advance for your replies. Have a nice day โ˜บ

Test with IE11:
scr1

Test with Chrome+Mobile mode:
scr2

Test with Chrome+Desktop mode:
scr3

SSR device detection is not working

I'm using react-device-detect in next.js (react SSR) but it doesn't work.

There are some closed issues about SSR in the repo but I think it isn't implemented yet.

next version: 9.0.5
react-device-detect: 1.9.10

navigator is not defined

When I start my app which use lib in latest version (1.11.14), I found error navigator is not defined. I think the problem is in main.js file.
var getNavigatorInstance = function getNavigatorInstance() { if (typeof window !== 'undefined') { if (window.navigator || navigator) { return window.navigator || navigator; } }
I try to remove it from node_modules then it's work. But I'm not sure we can remove it from code or not. Can anybody confirm it?

SSR Support

Hi,

I don't see a way to pass a custom user agent string into this library but it seems like it should be straightforward since you are using UA Parser. Allowing for this would enable use in SSR.

See https://github.com/faisalman/ua-parser-js#using-nodejs.

If you are open to this idea, I would be happy to help with a PR.

Best,

Jon

Ua-parser-js pipeline error

./node_modules/react-device-detect/main.js Cannot find module: 'ua-parser-js/dist/ua-parser.min'. Make sure this package is installed

I am getting this issue when I am running my pipeline and it just started today right after this commit-

900082e

I am not sure what would have caused it in the commit as there were no changes to the package.json other than the version

Kindle Fire HD not identified as mobile/tablet

img_3211

img_3213

As shown in the attached screenshot I've tested on two Kindle Fire HD tablets and both have the same outcome. isMobile/isTablet is false as the device type comes back as browser/desktop. I also went to https://faisalman.github.io/ua-parser-js/ on both Kindle fire's and they are identified as desktop/browser.

I'm thinking about checking for the Silk user agent on top of isMobile in my application for the time being, or os of Android... not sure if that will affect some Chrome books?

FYI, if you just test with the emulation in chrome dev tools for the Kindle Fire HD you will get the desired isMobile/Tablet: true, device is Amazon... you have to test on an actual device, and the BrowserStack emulator, if you can get it to load, will give you browser generic device/desktop as well on ua-parser-js.

please add function that returns the device type

Instead of returning the object with the value key of the device set to true, please create a function that would just return the device type as a string.

ex: returnDeviceType();

-> 'isMobile' or Mobile of whatever.

This no longer works on iOS

When testing a device in a hybrid app via xcode the deviceType returns as browser even though it is a native ios app.

SSR Support

Hi! I saw a closed issue that was about implementing SSR detection: is there any updates on this? Thanks! :)

Why device is needed in props for view

<BrowserView device={isBrowser}>
    <h1> This is rendered only in browser </h1>
</BrowserView>
<MobileView device={isMobile}>
    <h1> This is rendered only on mobile </h1>
</MobileView>

Why cant BrowserView/any view component check whether the device is browser / its respetive device internally so that the usage will be simple.

<BrowserView>
    <h1> This is rendered only in browser </h1>
</BrowserView>
<MobileView>
    <h1> This is rendered only on mobile </h1>
</MobileView>

Generic type ReactComponentElement error

throw typescript error with latest packages below;

  • "react-device-detect": "^1.9.9",
  • "@types/react": "16.9.2",

ERROR in ..../node_modules/react-device-detect/index.d.ts ERROR in .../node_modules/react-device-detect/index.d.ts(75,53): TS2707: Generic type 'ReactComponentElement<T, P>' requires between 1 and 2 type arguments.

it could be ok just adding <any> to line 75 of index.d.ts

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.