Skip to content

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.
ts
import { trackMediaQuery } from '@withease/web-api';

const { $matches, matched } = trackMediaQuery('(max-width: 600px)', {
  setup: appStarted,
});

Returns an object with:

  • $matches: Store with true if query is matches current state and false if it is not
  • matched: 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.

ts
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:

ts
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.

<script setup>
import { trackMediaQuery } from '@withease/web-api';
import { createEvent } from 'effector';
import { useUnit } from 'effector-vue/composition';
import { onMounted } from 'vue';

const appStarted = createEvent();

const mq = trackMediaQuery('(max-width: 320px)', {
  setup: appStarted,
});

const matchesSmall = useUnit(mq.$matches);

onMounted(appStarted);
</script>

<template>
  <p v-if="matchesSmall">Query matches small viewport</p>
  <p v-else>Query matches normal viewport</p>
</template>

Released under the MIT License.