1

I need to un-render some react component for mobile user

How to un-render component when user come from mobile device?

Thanks

1 Answers1

5

I think this would be a simple solution:

Outside component:

var isMobile = {
    Android: function() {
        return navigator.userAgent.match(/Android/i);
    },
    BlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    iOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    Opera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    Windows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

Inside component:

React.createClass({
  getInitialState: function() {
    return {
      isMobile: isMobile.any(),
      ...
    }
  },
  ...
  render: function() {
    { // base the display of the component on the boolean this.state.isMobile

If the if/else becomes more complex than a simple ternary, be sure to move it out of render() to a helper.

Hope this helps!

Edit: This could help with your conditional rendering if that isn't something you've done a ton of. How to load components conditionally in ReactJS

Mobile testing code source: http://www.abeautifulsite.net/detecting-mobile-devices-with-javascript/

Community
  • 1
  • 1
Andrelton
  • 150
  • 1
  • 8
  • That doesn't unmount the component, like OP wanted. – Michael Parker Aug 05 '15 at 23:01
  • 1
    True -- if 'not rendering' isn't what you're looking for, you can use the same logic outside the component, but use this: React.unmountComponentAtNode(document.getElementById('mobile-container')); – Andrelton Aug 05 '15 at 23:06
  • @Andrelton You might want to give [proper attribution](http://stackoverflow.com/a/13819253/2054072) about a huge part of your answer... – Preview Nov 25 '16 at 06:51