Browser Detection in ReactJS
This is the service I always use when doing JS/Browser based browser-detection: http://is.js.org/
if (is.ie() || is.edge()) {
window.location.href = 'http://example.com';
}
I was using Gatsby for our React site and build was giving me trouble with the accepted answer, so I ended up using a useEffect
on load to be able to not render for IE at a minimum:
const [isIE, setIsIE] = React.useState(false);
React.useEffect(() => {
console.log(`UA: ${window.navigator.userAgent}`);
var msie = window.navigator.userAgent.indexOf("MSIE ");
setIsIE(msie > 0)
}, []);
if(isIE) {
return <></>
}
// In my component render
if(isIE) { return <></> }
Got the idea originally from:
https://medium.com/react-review/how-to-create-a-custom-usedevicedetect-react-hook-f5a1bfe64599
and
Check if user is using IE
You are on the right track you can use these to conditionally render jsx or help with routing...
I have used the following with great success.
Originally from - How to detect Safari, Chrome, IE, Firefox and Opera browser?
// Opera 8.0+
const isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Firefox 1.0+
const isFirefox = typeof InstallTrigger !== 'undefined';
// Safari 3.0+ "[object HTMLElementConstructor]"
const isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification));
// Internet Explorer 6-11
const isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+
const isEdge = !isIE && !!window.StyleMedia;
// Chrome 1 - 71
const isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);
// Blink engine detection
const isBlink = (isChrome || isOpera) && !!window.CSS;
Please be aware they each stand a chance to deprecated due to browser changes.
I use them in React like this:
content(props){
if(!isChrome){
return (
<Otherjsxelements/>
)
}
else {
return (
<Chromejsxelements/>
)
}
}
Then by calling {this.Content()} in my main component to render the different browser specific elements.
Pseudo code might look something like this... (untested):
import React from 'react';
const isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);
export default class Test extends React.Component {
content(){
if(isChrome){
return (
<div>Chrome</div>
)
} else {
return (
<div>Not Chrome</div>
)
}
}
render() {
return (
<div>Content to be seen on all browsers</div>
{this.content()}
)
}
}
Not sure why but nobody mentioned this package: react-device-detect The package have a lot browsers checks, plus versions and some other info related. It's really small and it's updated.
You can use:
import { isIE } from 'react-device-detect';
isIE // returns true or false
react-device-detect it's also very small bundlephobia link