JS MQ match
JS MQ Match is a simple package that leverages window.matchMedia API.
It provides a wrapper on top of this API.
This wrapper is a static class, that allows subscribing / unsubscribing from a media query.
How to consume it
In order to consume this simple package, you first need to install it:
npm i js-mq-match
After you installed it in your app, wherever you need to listen to media queries you just call the subscribe method of the static class.
import { MediaQueryListener } from 'js-mq-match';
const handler = (matches) => {
console.log('Query matches ', matches);
}
const query = '(max-width: 768px)';
MediaQueryListener.subscribe(handler, query);
MediaQueryListener.unsubscribe(handler, query);
How it works
Being a global static class, whenever you subscribe from somewhere within the code to a specific query, it checks if there is already a subscription to the query:
- if there is not, it will add the callback as the first subscriber to the query, and add a
change event
listener for that query, which will call all of the subscribed callbacks on changes.
- if there is, it will just push the callback to the list of subscribers for that query.
It will also call the callback with the initial value (before change events happen).
When unsubscribe method is called, it removes the callback from the subscription list for that query, and
if it reaches a point where there are no more subscribed callbacks, it will remove the event listener created in the initial subscribe call for that query.