🌈 Easy-to-use media queries for your React project

Overview

npm version npm downloads License

🌈   React Super Simple Media Queries

Easy-to-use media queries for your React project

Features

  • ⚡️   Fast & Light with MatchMedia API ⚡️
  • 🕶   Auto detects the device viewport from Cookie & User-Agent
  • 👌   Zero configuration to start
  • 👴️   Supports IE9+

Quick Setup

  1. Add react-superq dependency to your project
# Using npm
npm add react-superq
# Using yarn
yarn add react-superq
# Using pnpm
pnpm add react-superq
  1. Wrap your application with MediaQueryProvider
+ import { MediaQueryProvider } from 'react-superq'

const root = ReactDOM.createRoot(document.getElementById('root'))

root.render(
  
+   
      
+   
  
)
  1. Use useMediaQuery in any component!
// App.tsx

import React, { useMemo } from 'react'
import { useMediaQuery } from 'react-superq'

const App: React.FC = () => {
  const mediaQuery = useMediaQuery()

  // You can use it in your code.
  const isDesktopOrHigher = useMemo(() => {
    return mediaQuery.isLessThan('desktop') && mediaQuery.isGreaterThan('mobileWide')
  }, [mediaQuery.breakpoint])

  return (
    <div>
      <h1>This is my App!</h1>

      {/* Or directly in the markup! */}
      {mediaQuery.isLessThan('tablet') && <div>I will be visible only on mobile!</div>}
    </div>
  )
}

Quick Setup for Next.JS

  1. Add react-superq dependency to your project
# Using npm
npm add react-superq
# Using yarn
yarn add react-superq
# Using pnpm
pnpm add react-superq
  1. Wrap your application with MediaQueryProvider & initialize the MediaQueryManager (for SSR)

Before

// pages/_app.tsx

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <Component {...pageProps} />
  )
}

After

// pages/_app.tsx

import { MediaQueryManager, MediaQueryProvider } from 'react-superq'

type InitialProps = {
  contextBreakpoint: string
}

const mediaQueryManager = new MediaQueryManager()

function MyApp({ Component, contextBreakpoint, pageProps }: AppProps & InitialProps) {
  return (
    <MediaQueryProvider contextBreakpoint={contextBreakpoint}>
      <Component {...pageProps} />
    </MediaQueryProvider>
  )
}

// Detect the breakpoint on the server.
MyApp.getInitialProps = async ({ ctx }: AppContextType) => {
  const contextBreakpoint = await mediaQueryManager.detectBreakpoint(
    ctx.req?.headers.cookie,
    ctx.req?.headers['user-agent'],
  )

  return {
    contextBreakpoint,
  } as InitialProps
}

Tune-up the MediaQueryManager

Note
You can initialize an endless amount of MediaQueryManager, but each new one will refer to the first one.

const mediaQueryManager = new MediaQueryManager({
  // ...
})

Configuration

breakpoints

  • Type: Object

An object where the key is the name of the mediaQuery, and the value is the breakpoint size.

cookieName

  • Type: String
  • Default: breakpoint

The key for the document cookie.

defaultBreakpoints

  • Type: Object
  • Detectable devices: console, desktop, embedded, mobile, smarttv, tablet, wearable

An object where the key is the name of the detected device, and the value is the breakpoint key.

fallbackBreakpoint

  • Type: String
  • Default: desktop

The breakpoint key to be used, if the device was not detected.

Default configuration

{
  breakpoints: {
    desktop: 1024,
    desktopMedium: 1280,
    desktopWide: 1600,

    mobile: 320,
    mobileMedium: 375,
    mobileWide: 425,

    tablet: 768,
  },

  cookieName: 'breakpoint',

  defaultBreakpoints: {
    desktop: 'desktop',
    mobile: 'mobile',
    tablet: 'tablet',
  },

  fallbackBreakpoint: 'desktop',
}

Presets

API

MediaQueryManager

  • detectBreakpoint(cookie?: string, userAgent?: string): Promise
  • getMediaQueries(): Record
  • usePreset(key: keyof typeof PRESETS): MediaQueryManager>

MediaQueryManagerOptions

  • defaultBreakpoints: Partial>
  • breakpoints: Record
  • cookieName: string
  • fallbackBreakpoint: string

useMediaQuery

  • readonly breakpoint: string
  • isGreaterThan(input: string): boolean
  • isGreaterOrEquals(input: string): boolean
  • isLessThan(input: string): boolean
  • match(input: string): boolean
  • matches(...input: string[]): boolean

License

MIT License

Copyright (c) mvrlin [email protected]

You might also like...
A lightweight react library that converts raw HTML to a React DOM structure.

A lightweight react library that converts raw HTML to a React DOM structure.

React-intersection-observer - Intersection observer With React
React-intersection-observer - Intersection observer With React

react-intersection-observer Package 📦 Copy and Paste the Framer Package Usage F

React-compress - This compress library was made with Brotli and Gzip help, for React users who want to make website more performance and reduce JS bundle code
React-compress - This compress library was made with Brotli and Gzip help, for React users who want to make website more performance and reduce JS bundle code

React-compress - This compress library was made with Brotli and Gzip help, for React users who want to make website more performance and reduce JS bundle code

React adblocker detect - Provides you with react hook to detect is an adblocker is enabled

React adblocker detect - Provides you with react hook to detect is an adblocker is enabled

A react or react native library to call functions comparing the last time that it was called
A react or react native library to call functions comparing the last time that it was called

A react or react native library to call functions comparing the last time that it was called and running it when it's really needed. Avoiding unnecessary database calls or data loads that are updated at a certain time.

React-native-dotenv - Load react native environment variables using import statements for multiple env files.

react-native-dotenv Load environment variables using import statements. Installation $ npm install react-native-dotenv Breaking changes: moving from v

Extended utils for ⚛️  React.Children data structure that adds recursive filter, map and more methods to iterate nested children.
Extended utils for ⚛️ React.Children data structure that adds recursive filter, map and more methods to iterate nested children.

React Children Utilities Recursive and extended utils for React children opaque data structure. Installation Available as a package and can be added t

A component for React that utilizes the Counterpart module to provide multi-lingual/localized text content.

React Translate Component Translate is a component for React that utilizes the Counterpart module and the Interpolate component to provide multi-lingu

A static site generator powered by Deno + React
A static site generator powered by Deno + React

A static site generator powered by Deno + React

Owner
Igor Talpa
🥷 Lead Frontend Developer
Igor Talpa
A streamlined way of creating a React.Context based on a schema. Easy to use and with 0 dependencies.

A streamlined way of creating a React.Context based on a schema. Easy to use and with 0 dependencies.

André Batista 3 Sep 6, 2022
React code splitting made easy. Reduce your bundle size without stress ✂️ ✨ .

React code splitting made easy. Reduce your bundle size without stress ✂️ ✨ . npm install @loadable/component Docs See the documentation at loadable-c

Greg Bergé 6.8k Sep 24, 2022
Superjson-remix: A solution for Remix that allows you to send binary data from your loader function to your React client app

superjson-remix A solution for Remix that allows you to send binary data from your loader function to your React client app. It uses the awesome super

Donavon West 66 Sep 13, 2022
👉 React Finger is a library of gesture events for React that allows developers to use a single set of events for both desktop and mobile devices.

?? React Finger is a library of gesture events for React that allows developers to use a single set of events for both desktop and mobile devices.

Houfeng 5 Jul 11, 2022
A QRCode component for use with React.

qrcode.react A React component to generate QR codes. Installation npm install qrcode.react Usage var React = require('react'); var QRCode = require('q

Paul O’Shannessy 3.1k Sep 29, 2022
A helper library to use react-query more efficient, consistency

A helper library to use react-query more efficient, consistency

null 138 Aug 9, 2022
This project allows you leverage Million's Virtual DOM while writing React code

This project allows you leverage Million's Virtual DOM while writing React code. Get faster rendering (a compiler optimizes virtual DOM beforehand) while ensuring the same developer experience React provides.

Aiden Bai 白宇彤 354 Sep 15, 2022
@custom-elements-manifest/analyzer plugin to ✨ automatically ✨ create react wrappers for your custom elements

cem-plugin-reactify @custom-elements-manifest/analyzer plugin to automatically create React wrappers for your custom elements based on your custom ele

Pascal Schilp 9 Jul 29, 2022
React-Native library for the WidgetKit framework. Integrate a Widget into your App 🍏📱

react-native-widgetkit React-Native Library for the iOS ?? WidgetKit framework Table of Contents ?? Introduction ??‍?? Installation ??‍ Usage ????‍??

Fasky 110 Sep 20, 2022
Because your state management code should be domain-agnostic.

Because your state management code should be domain-agnostic.

Zachary DeRose 11 Sep 23, 2022