/use-breakpoint

A React hook for getting the current responsive media breakpoint

Primary LanguageTypeScriptMIT LicenseMIT

use-breakpoint

GitHub Actions version code size dependencies devDependencies

A React hook (>=16.8) for getting the current responsive media breakpoint, successor to breakpoint-observer.

Usage

Initialize useBreakpoint with a configuration object, and optionally a default breakpoint name (in non-window environments like SSR). The return value will be an object with the breakpoint's name (string), min-width, and max-width values (number):

import useBreakpoint from 'use-breakpoint';

...

const CurrentBreakpoint = () => {
  const {
    breakpoint,
    maxWidth,
    minWidth
  } = useBreakpoint(
    { mobile: 0, tablet: 768, desktop: 1280 },
    'desktop'
  );

  return (
    <p>The current breakpoint is {breakpoint}!</p>
  );
};

Functionality

This component uses the window.matchMedia functionality to calculate the current breakpoint. For a list of breakpoints, we generate some css media queries in the form of (min-width: XXXpx) and (max-width: YYYpx) and then add listeners for the changes. useBreakpoint will then update its return value when the breakpoint changes from one rule to another.

Developing

This project is built with Typescript. A Storybook is included for local previewing. The easiest way to get started is cloning the repo and starting the storybook server locally via npm start.