1.0.6 ā€¢ Published 2 years ago

use-breakpoint-observer v1.0.6

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

useBreakpointsObserver()

šŸœ 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]
ArgumentTypeRequired?Description
htmlRefReact.RefObject | nullYesA React ref created by useRef() or nullto observe the HTML body element
breakpointsBreakSizesType (Object)YesAn 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

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago