Skip to main content

createMediaQuery

Create a reactive boolean accessor tracking the match status of any CSS media query.

View as Markdown

createMediaQuery returns a reactive boolean accessor that tracks whether a CSS media query matches. It updates when the query’s match state changes.

Import#

import { createMediaQuery } from 'moraine/utils'

Signature#

function createMediaQuery(query: string | Accessor<string>, defaultValue = false): Accessor<boolean>

Usage Example#

src/ResponsiveLayout.tsx
import { Show } from 'solid-js'
import { createMediaQuery } from 'moraine/utils'

export function ResponsiveLayout() {
  const isMobile = createMediaQuery('(max-width: 768px)', false)

  return (
    <Show when={isMobile()} fallback={<div>Desktop Navigation</div>}>
      <div>Mobile Drawer Navigation</div>
    </Show>
  )
}

Features#

  • Returns defaultValue during server rendering and until the first client effect runs, so server and hydrated markup match. It then reads the real match state and subscribes to changes with matchMedia.
  • The query argument may be an accessor, so the tracked query can change reactively (for example, () => isDesktop() ? '(min-width: 1024px)' : '(min-width: 640px)').
  • Accepts a query with a leading @media; the prefix is stripped.
  • Removes the media listener when the Solid owner disposes or the query changes.
  • Stays at defaultValue when window.matchMedia is unavailable.