npm.io
1.0.6 • Published 3 years ago

use-breakpoint-observer

Licence
MIT
Version
1.0.6
Deps
1
Size
9 kB
Vulns
0
Weekly
0

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

Keywords