A remedy for media queries in React.
Remedia provides an API for Media Queries that treats JavaScript and React as a first class citizens with CSS. Rather than being defined as strings, Media Queries are defined as MediaQuery
objects that can later be combined to make new Media Queries or who's values can be referenced in other contexts.
Remedia is written in TypeScript providing a type safe API and a great developer experience. It makes use of generics and literal types to make it easy to inspect a query's underlying data just by looking at its type information:
npm install remedia
import remedia from 'remedia';
const phoneLargeMin = remedia({ minWidth: 321 });
const style = css`
font-size: 12px;
@media ${phoneLargeMin} {
font-size: 16px;
}
`;
MediaQuery
instances become actual media query strings when they are interpolated, which calls thetoString()
method underneath
const MyComponent: React.FC = () => {
// `use` method defaults to false
const matchesPhoneLargeMin = phoneLargeMin.use()
// but you can pass true to default to true
const matchesPhoneLargeMax = phoneLargeMin.use(true)
...
}
const tabletLandscapeMin = remedia({ minWidth: 769 });
const tabletLandscapeMax = remedia({ maxWidth: 1024 });
const tabletLandscapeRange = remedia({
...tabletLandscapeMin,
...tabletLandscapeMax,
});
If you need to OR multiple queries together, just pass multiple queries into remedia.
/* small phone portrait: *-320 */
export const phoneSmallMax = remedia({ maxWidth: 320 });
/* tablet portrait: 569–768 */
export const tabletMin = remedia({ minWidth: 569 });
export const tabletMax = remedia({ maxWidth: 768 });
// compound query using OR and built from previous queries: 0-114 or 569-768
export const narrowMainContent = remedia(phoneSmallMax, {
...tabletMax,
...tabletMin,
});
In the process of building this library I was inspired by and borrowed ideas & code from @jaredpalmer's useMedia
hook.
This library also includes a forked and modified version of the great json2mq
library by @kiran.