Git Product home page Git Product logo

react-useragent's Introduction

react-useragent

Integrate user-agent detection in an idiomatic React way.

Installation

yarn add @quentin-sommer/react-useragent or npm i -s @quentin-sommer/react-useragent

For React 15 (old context) use the 2.x version

// React 15
"dependencies": {
  ...
  "@quentin-sommer/react-useragent": "^2.0.0"
  ...
}

Introduction

Imagine being able to render magnificent, deep links, beautiful download buttons for your app. Well, Now you can.

<div>
  <UserAgent ios>
    <BeautifulIOSButton />
  </UserAgent>
  <UserAgent windows>
    <BeautifulWindowsButton />
  </UserAgent>
</div>

react-useragent wraps the great UAParser.js library and make it easy to use useragent knowledge inside your React applications. react-useragent provides useful shortcuts but you can always use an escape hatch in case you want to access the underlying library.

live demo

Usage

Next.js example

The most common question about this library is how to use it with Next.js. An example is available in an issue.

Generic usage

First you need to wrap your App in a <UserAgentProvider> tag. You also need to pass a user agent string to <UserAgentProvider>. On the browser that would be window.navigator.userAgent.

react-useragent works in server side rendering as well, just pass it the request useragent string. On express that would be req.headers['user-agent'].

import {UserAgentProvider} from '@quentin-sommer/react-useragent'

const App = props => (
  <UserAgentProvider ua={window.navigator.userAgent}>
    <div>{/* rest of your App */}</div>
  </UserAgentProvider>
)

Then use the <UserAgent> component.

react-useragent expose some props, these are optimized and using them will be faster than directly accessing the UAParser.js library.

Available props for <UserAgent>

  • computer
  • windows
  • linux
  • mac
  • mobile
  • tablet
  • android
  • ios
  • firefox
  • chrome
  • edge
  • safari

Theses props are cumulable : <UserAgent firefox mobile> will match both firefox browser and mobile systems.

import {UserAgentProvider, UserAgent} from '@quentin-sommer/react-useragent'

const App = props => (
  <UserAgentProvider ua={window.navigator.userAgent}>
    <div>
      <UserAgent mobile>
        <p>This will only be rendered on mobile</p>
      </UserAgent>
    </div>
  </UserAgentProvider>
)

You can also use this alternative API if you find it more convenient

<UserAgent mobile>
    {uaIsMobile => (
        {uaIsMobile && <p>This will ONLY be rendered on mobile</p>}
        {!uaIsMobile && <p>This will NOT be rendered on mobile</p>}
    )}
</UserAgent>

For full power you can always access the underlying parser with the returnFullParser prop

<UserAgent returnFullParser>
  {parser => (
    <p>
      I see you, {parser.getOS().name} {parser.getCPU().architecture}
    </p>
  )}
</UserAgent>

You can also use the library with the useContext hook

import {UAContext} from '@quentin-sommer/react-useragent'
const UsingContextHook = () => {
  const {uaResults, parser} = useContext(UAContext)
  return parser.getOS().name
}

For more example see the demo app source here

If you have any questions don't hesitate to say hi on Twitter

react-useragent's People

Contributors

dependabot-preview[bot] avatar dependabot[bot] avatar greenkeeper[bot] avatar jessepinho avatar quentin-sommer 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

react-useragent's Issues

Build errors on Next.js 13 and above

With major changes to React 18 and a heavy reliance on React Server Components on Next.js 13, it causes the build to fail even with "use client"; directive, specifically throwing a prerender error

Screenshot 2023-09-28 122333

Another solution I've tried to use next/dynamic with dynamic(() => import("@quentin-sommer/react-useragent").then((c) => c.UserAgentProvider), { ssr: false }) but to no avail, still give me the same previous error

Usage behind a CDN

CDNs usually don't forward the user-agents to the servers, or they override it with their own user-agent, usually ins this situation, they send some custom headers with the requisition, cloudfront for example:

CloudFront-Is-Mobile-Viewer
CloudFront-Is-Tablet-Viewer
CloudFront-Is-Desktop-Viewer

Would a feature that allows the developer to pass in their own custom uaresults to the provider or something similar make sense in this case?

A workaround / alternative I'm using in the moment is to just fake a ua in the code and pass it down to the provider...

if (userAgent === 'Amazon CloudFront') {
  userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36';
  if (props.ctx.req.headers['cloudfront-is-tablet-viewer'] === 'true') {
    userAgent = 'Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit/604.1.34 (KHTML, like Gecko) Version/11.0 Mobile/15A5341f Safari/604.1';
  } else if (props.ctx.req.headers['cloudfront-is-mobile-viewer'] === 'true') {
    userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1';
  }
}

Great library btw, ty for making it open sourced.
Feel free to close it if you think the dev should just use the workaround, just posting this to bring up some ideas and a place where ppl can find a workaround if they face this problem.

Error when testing with Page Speed Insight

When testing page in https://developers.google.com/speed/pagespeed/insights

Site gets error with react-useragent

TypeError undefined is not a function
webpack:///node_modules/@quentin-sommer/react-useragent/es/UserAgent.js:17
  | props = _objectWithoutProperties(_ref, ['children', 'returnfullParser']);
  |  
  | var validProps = Object.keys(props).filter(function (prop) {
  | return availableProps.includes(prop);
  | });
  | var ret = validProps.some(function (prop) {
  | return ua.uaResults[prop];

An in-range update of react is breaking the build 🚨

There have been updates to the react monorepo:

    • The devDependency react was updated from 16.6.1 to 16.6.2.
  • The devDependency react-dom was updated from 16.6.1 to 16.6.2.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

This monorepo update includes releases of one or more dependencies which all belong to the react group definition.

react is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build could not complete due to an error (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

https://app.leanboard.io/board/f80118c3-5747-4759-8904-6bf5cca7b619
LeanBoard

Bump React version

I'm getting an error installing on a react 18 project. Is it possible update this project to support installing in a react 18 project please?

Version 10 of node.js has been released

Version 10 of Node.js (code name Dubnium) has been released! 🎊

To see what happens to your code in Node.js 10, Greenkeeper has created a branch with the following changes:

  • Added the new Node.js version to your .travis.yml

If you’re interested in upgrading this repo to Node.js 10, you can open a PR with these changes. Please note that this issue is just intended as a friendly reminder and the PR as a possible starting point for getting your code running on Node.js 10.

More information on this issue

Greenkeeper has checked the engines key in any package.json file, the .nvmrc file, and the .travis.yml file, if present.

  • engines was only updated if it defined a single version, not a range.
  • .nvmrc was updated to Node.js 10
  • .travis.yml was only changed if there was a root-level node_js that didn’t already include Node.js 10, such as node or lts/*. In this case, the new version was appended to the list. We didn’t touch job or matrix configurations because these tend to be quite specific and complex, and it’s difficult to infer what the intentions were.

For many simpler .travis.yml configurations, this PR should suffice as-is, but depending on what you’re doing it may require additional work or may not be applicable at all. We’re also aware that you may have good reasons to not update to Node.js 10, which is why this was sent as an issue and not a pull request. Feel free to delete it without comment, I’m a humble robot and won’t feel rejected 🤖


FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

An in-range update of prop-types is breaking the build 🚨

The devDependency prop-types was updated from 15.6.2 to 15.7.0.

🚨 View failing branch.

This version is covered by your current version range and after updating it in your project the build failed.

prop-types is a devDependency of this project. It might not break your production code or affect downstream projects, but probably breaks your build or test tools, which may prevent deploying or publishing.

Status Details
  • continuous-integration/travis-ci/push: The Travis CI build failed (Details).

FAQ and help

There is a collection of frequently asked questions. If those don’t help, you can always ask the humans behind Greenkeeper.


Your Greenkeeper Bot 🌴

Including Oculus Browser

With more increase of VR headset sales, it would be nice to include Oculus Browser. Is there any chance someone like me can assist through a PR to include the Oculus Browser in this library?

How to use it without <UserAgent>?

Good evening.

Is there some 'isMobile' variable available? I searched in source code but found nothing.
Sometimes we need to add className depending if isMobile or not; or do some logical before render; others I use <UserAgent>.

Nice work, thank you =)

Useragent on static sites (next.js export)

Hi Quentin,

Thanks for the package!

I have UserAgent working perfectly in development for my Next.js app, I used your example _app.js file to get started.

However, when I come to export to a static site the useragent doesn't work (i'm guessing because this is only available client-side).

Is there a work-around this or is useragent just generally unavailable for statically generated sites?

Thanks!

Update: Next.js docs https://nextjs.org/docs/advanced-features/static-html-export

With next export, we build an HTML version of your app. At export time we will run the getInitialProps in your pages. The req and res fields of the context object will be empty objects during export as there is no server running.

Wrong prop name on README

Hello!

I think I've spotted a small issue.

The readme states that in order to get the parser one should pass the property returnFullParser to the component UserAgent, but instead it works only with returnfullParser .

Export simple boolean or object

Hey, I just stumpled upon your library and it's great I am going to use it for my Next.js application. One question though: Would it be possible to export a simple boolean like: isMobile or an object or something?

Bump React version

The project is already using the types/react v17. Is it possible to bump the react version too to 17 and update the peer dependency? I'm getting an error installing on a react 17 project.

negated props?

Hi @quentin-sommer, firstly, thank you for creating this useful library!

In a particular use-case, I was looking to target only a mobile phones, but not tablets. Unfortunately, I noticed that the mobile prop is set to true on both mobile and tablet devices.

So, in such a case, what do you recommend? Would you consider adding a false value such that the code below would target only say mobile phones:

<UserAgent mobile tablet = { false } /> 

If so, that would be useful for people who want to target only certain browsers on certain mobile devices as this would provide the desired flexibility?

Thank you!

Next 9 warns opted-out Automatic Prerendering

Based on your example next example,
The example is using getInitialProps,this gets warn.

Warning: You have opted-out of Automatic Prerendering due to `getInitialProps` in `pages/_app`.

 Read more: https://err.sh/next.js/opt-out-automatic-prerendering

Is there anyway to comply with the warning?

Thanks,

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.