Media query
Allows tracking any media query matching state with Events and Stores.
INFO
Uses Window.matchMedia under the hood
Usage
Single query
All you need to do is to create an integration by calling trackMediaQuery
with query to track an integration options:
setup
: after this Event all listeners will be installed, and the integration will be ready to use; it is required because it is better to use explicit initialization Event in the application.teardown?
: after this Event all listeners will be removed, and the integration will be ready to be destroyed.
import { trackMediaQuery } from '@withease/web-api';
const { $matches, matched } = trackMediaQuery('(max-width: 600px)', {
setup: appStarted,
});
Returns an object with:
$matches
: Store withtrue
if query is matches current state andfalse
if it is notmatched
: Event fired when query starts to match current state
TIP
It supports @@trigger
protocol. Since it allows firing only one Event trackMediaQuery
triggers matched
as a fired
in case of @@trigger
protocol.
import { trackMediaQuery } from '@withease/web-api';
somethingExpectsTrigger(trackMediaQuery('(max-width: 600px)'));
To use it as a @@trigger
protocol you do not have to pass setup
and teardown
options.
Multiple queries
You can track multiple queries by calling trackMediaQueries
with queries to track and integration options:
import { trackMediaQuery } from '@withease/web-api';
const { mobile, desktop } = trackMediaQuery(
{ mobile: '(max-width: 600px)', desktop: '(min-width: 601px)' },
{ setup: appStarted }
);
mobile.$matches; // Store<boolean>
mobile.matched; // Event<void>
desktop.$matches; // Store<boolean>
desktop.matched; // Event<void>
Live demo
Let us show you a live demo of how it works. The following demo displays a $matches
value of the query in the screen. Change the screen size to see how it works.