MadeInHaus / react-starter

A client-side SPA starter bundled with React, Redux, CSS Modules, React Router 4, and Webpack 4
MIT License
9 stars 2 forks source link

Share variables between styles and JS #3

Closed ClayCooperLA closed 6 years ago

ClayCooperLA commented 7 years ago

Need a way of accessing the sass media query values from javascript for media matching in renders.

React Media (https://www.npmjs.com/package/react-media) is great for matching media in render.

There is just one confusing thing we should keep in mind, if we are rendering something that only exists in mobile and is removed in tablet+, we have to use maxWidth with 1px less in value than the equivalent minWidth media query value. The following explains:

When we need to render something in mobile that doesn't exist in tablet+, we have to use maxWidth: 767. It does not allow ! minWidth: 768. In css this would normally be something that exists from 0-767px and is removed with a cascading rule at minWidth: 768, which means do not exist after or equal to 768. But, when conditionally rendering in javascript it doesn't make sense to override/cascade, we simply tell it to exist at maxWidth: 767 and we avoid having to tell it to render nothing at minWidth: 768, like css would.

If we are rendering different content on both sides of the media query, React Media has an option to match the media in a ternary. Then it doesn't matter if we use maxWidth or minWidth, since we must render something in both conditions. However, it may make sense to champion use of minWidth for this because that falls more in line with how css is written in mobile first. A minWidth: 768 match will "override" the non matching (0-767px) render like a css cascade. Rather than just using maxWidth: 767 every time we use React Media. Especially since rendering something extra in mobile only is fairly rare.

TLDR: The maxWidth value is always 1 less than the equivalent minWidth value. Use minWidth in React Media when rendering different content on both sides of the media query, must use maxWidth when rendering only in mobile, and minWidth when rendering only in tablet+.

chrisjcodes commented 6 years ago

Closing as this can be achieved with :exports in CSS Modules