0

I love react-responsive for its MediaQuery component which I can use as such:

<MediaQuery maxDeviceWidth={480}>
  <button> Only show this on mobile </button>
</MediaQuery>

But what about in a function, like an event handler, when I want to do something based on if I'm on mobile or not?

For example, in the layout I have for mobile, I want a scroll to happen when selecting one of the elements. This scroll doesn't make sense in the desktop layout. So one of my click handlers should be something like:

onClick = () => {
  if (responsive.isMobile()) {
    window.scrollTo(0);
  }
}

How can I achieve this?

tscizzle
  • 11,191
  • 15
  • 54
  • 88

1 Answers1

1

You may not have to rely on react-responsive library for this feature. You could detect the device width with vanilla javascript and determine for yourself if it's what you would consider 'mobile'.

Now there are many ways around this, to be honest, my suggestion about is just one solution. Discussions around this can lead you deep into the rabbit hole

For simplicities sake, here's a potential solution

onClick = () => {
  if (window.innerWidth <= 480) 
    window.scrollTo(0)
}
jkris
  • 5,851
  • 1
  • 22
  • 30