0.1.0 • Published 2 years ago
@m87wheeler/use-media-query v0.1.0
useMediaQuery Hook
This hook aims to make updating values based on media queries directly in a React component as simple but flexible as possible.
How to Use
- Import the hook as a default import:
import useMediaQuery from '@m87wheeler/use-media-query';
There are also 2 additional imports available as named imports:
import useMediaQuery, {
IBreakpoints,
initialBreakpoints,
} from '@m87wheeler/use-media-query';
- Inside your React component, use the hook:
const value = useMediaQuery([]);
- The first argument in the hook is a required array. This should be an array of up to 6 values (any type is accepted):
const value = useMediaQuery([1, 2, '3', 'four', { num: 5 }, 6]);
- The second argument in the hook is an optional object. The structure of this object is of type
IBreakpoints
(a TS interface) and, when not provided explicitly, is set toinitialBreakpoints
as default:
const value = useMediaQuery([1, 2, '3', 'four', { num: 5 }, 6], {
xs: 0,
sm: 576,
md: 768,
lg: 992,
xl: 1200,
xxl: 1400,
});
The six values in the array (first provided argument) represent, in order, the value returned at the corresponding breakpoint in the given object:
xs = 1;
sm = 2;
md = '3';
lg = 'four';
xl = { num: 5 };
xxl = 6;
- This value can then be used in your React component, and is updated as the window is resized.
Optional Breakpoints Object
The optional breakpoints object can be provided as a complete object, or a Partial
of the IBreakpoints
interface.
For example, the following is valid and will only override the given values in the default object:
const value = useMediaQuery([1, 2, 3, 4, 5, 6], { xm: 400, xxl: 1880 });
Progressive Array Values
The provided array will be automatically cut off at 6 items, for example:
const value = useMediaQuery([1, 2, 3, 4, 5, 6, 7, 8, 9]); // ignored = [7, 8, 9]
You can also pass an array of less than 6 items. The remaining values will inherit the last value given. For example:
const value = useMediaQuery([1, 2, 3, 4]); // array = [1, 2, 3, 4, 4, 4]
Future additions
Values as an object
const value = useMediaQuery({ sm: 1, lg: 4, xxl: 8 });
0.1.0
2 years ago