ReactTraining / react-media

CSS media queries for React

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

could you please explain the use cases when should we use this component instead of using regular css media queries. thanks

amanmavai opened this issue · comments

I'm using it for Server Side Rendering, so I don't render duplicate content.

There are lots of use cases, but I'll just mention a very basic one. Let's say you wanted to render a <SmallScreen> component when the screen is smaller than 400px, and a <LargeScreen> component when the screen is wider than 400px.

<Media query="(max-width: 399px)">
  {matches => (
    matches ? (
      <SmallScreen/>
    ) : (
      <LargeScreen/>
    )
  }
</Media>

This would allow you to easily decide which component to render based on the screen width.

Hope that helps!

Oh, just to add to @mjackson. If you would implement something similar using only CSS media queries, you would be forced to render both <SmallScreen />, as well as <LargeScreen />. Deciding which component to render in JS, allows you to prevent that performance hit.

@edorivai what you mentioned makes sense. I have a follow up question on how do we optimise for bundlesize? For example when my app is running on a small screen, ideally I shall only load SmallScreen and not load LargeScreen at all unless the screen size changes.

@kamleshchandnani I think regular bundle splitting with React.lazy() should work.