Skip to content

Commit

Permalink
Allow query argument to be an object
Browse files Browse the repository at this point in the history
  • Loading branch information
jacobrask committed Feb 9, 2019
1 parent 10fd268 commit 76f56db
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 3 deletions.
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@
import {useMedia} from 'use-media';

const Demo = () => {
const isWide = useMedia('(min-width: 1000px)');
// Accepts an object of features to test
const isWide = useMedia({ minWidth: 1000 });
// Or a regular media query string
const reduceMotion = useMedia('(prefers-reduced-motion: reduce)');

return (
<div>
Expand Down
28 changes: 26 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,33 @@ import * as React from 'react';

const { useState, useEffect } = React;

export const useMedia = (query: string, defaultState: boolean = false) => {
const [state, setState] = useState(defaultState);
type MediaQueryObject = { [key: string]: string | number | boolean };

const camelToHyphen = (str: string) =>
str.replace(/[A-Z]/g, m => `-${m.toLowerCase()}`).toLowerCase();

const objectToString = (query: string | MediaQueryObject) => {
if (typeof query === 'string') return query;
return Object.entries(query)
.map(([feature, value]) => {
feature = camelToHyphen(feature);
if (typeof value === 'boolean') {
return value ? feature : `not ${feature}`;
}
if (typeof value === 'number' && /[height|width]$/.test(feature)) {
value = `${value}px`;
}
return `(${feature}: ${value})`;
})
.join(' and ');
};

export const useMedia = (
rawQuery: string | MediaQueryObject,
defaultState: boolean = false
) => {
const [state, setState] = useState(defaultState);
const query = objectToString(rawQuery);
useEffect(() => {
let mounted = true;
const mql = window.matchMedia(query);
Expand Down

0 comments on commit 76f56db

Please sign in to comment.