use-breakpoint-observer
TypeScript icon, indicating that this package has built-in type declarations

1.0.6 • Public • Published

useBreakpointsObserver()

npm bundle size

🐜 Tiny size 🦄 Written in Typescript 😎 No timeouts or window.resize

A React hook that allows you to use a ResizeObserver and gives you access to the currently active breakpoint and the width dimension of the targeted html element or body

Install

npm install use-breakpoint-observer
yarn add use-breakpoint-observer

Basic Usage

import React from 'react';
import useBreakpointsObserver from './useBreakpointsObserver';

// Define the minimum width for each specific breakpoint name
const breakPointSizes = {
  xs: 480,
  sm: 576,
  md: 768,
  lg: 992,
  xl: 1200,
  xxl: 1600,
};

const App = () => {
  let observeRef = useRef(null);

  // call the Hook
  const [breakSize, width] = useBreakpointsObserver(
    observeRef,
    breakPointSizes,
  );

  return (
    <div ref={observeRef}>
      <p>
        Breakpoint is: {breakSize}
        <br />
        Width is: {width}
      </p>
    </div>
  );
};

Note: Pass a null htmlRef prop to observe the body element:

const [breakSize, width] = useBreakpointsObserver(null, breakPointSizes);

API

useResizeObserver(htmlRef, breakpoints)

const useBreakpointsObserver = <T extends HTMLElement>(
  htmlRef: React.RefObject<T> | null,
  breakpoints: BreakSizesType,
): [BreakPointsType, number | null]
Argument Type Required? Description
htmlRef React.RefObject | null Yes A React ref created by useRef() or nullto observe the HTML body element
breakpoints BreakSizesType (Object) Yes An Object that defines the minimum width for each specific breakpoint name

Types

breakpoints

export type BreakSizesType = {
  [key in BreakPointsType]?: number;
};

export type BreakPointsType = 'xs' | 'sm' | 'md' | 'lg' | 'xl' | 'xxl';

LICENSE

MIT

Package Sidebar

Install

npm i use-breakpoint-observer

Weekly Downloads

0

Version

1.0.6

License

MIT

Unpacked Size

8.71 kB

Total Files

11

Last publish

Collaborators

  • paulvaxevanis