npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-resize-detector

v10.0.1

Published

React resize detector

Downloads

6,466,744

Readme

Handle element resizes like it's 2024!

Live demo

Modern browsers now have native support for detecting element size changes through ResizeObservers. This library utilizes ResizeObservers to facilitate managing element size changes in React applications.

🐥 Tiny ~2kb

🐼 Written in TypeScript

🐠 Used by 160k repositories

🦄 Produces 100 million downloads annually

No window.resize listeners! No timeouts!

Is it necessary for you to use this library?

Container queries now work in all major browsers. It's very likely you can solve your task using pure CSS.

<div class="post">
  <div class="card">
    <h2>Card title</h2>
    <p>Card content</p>
  </div>
</div>
.post {
  container-type: inline-size;
}

/* Default heading styles for the card title */
.card h2 {
  font-size: 1em;
}

/* If the container is larger than 700px */
@container (min-width: 700px) {
  .card h2 {
    font-size: 2em;
  }
}

Installation

npm i react-resize-detector
// OR
yarn add react-resize-detector

Example

import { useResizeDetector } from 'react-resize-detector';

const CustomComponent = () => {
  const { width, height, ref } = useResizeDetector();
  return <div ref={ref}>{`${width}x${height}`}</div>;
};

With props

import { useResizeDetector } from 'react-resize-detector';

const CustomComponent = () => {
  const onResize = useCallback(() => {
    // on resize logic
  }, []);

  const { width, height, ref } = useResizeDetector({
    handleHeight: false,
    refreshMode: 'debounce',
    refreshRate: 1000,
    onResize
  });

  return <div ref={ref}>{`${width}x${height}`}</div>;
};

With custom ref

It's not advised to use this approach, as dynamically mounting and unmounting the observed element could lead to unexpected behavior.

import { useResizeDetector } from 'react-resize-detector';

const CustomComponent = () => {
  const targetRef = useRef();
  const { width, height } = useResizeDetector({ targetRef });
  return <div ref={targetRef}>{`${width}x${height}`}</div>;
};

API

| Prop | Type | Description | Default | | --------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------- | | onResize | Func | Function that will be invoked with width and height arguments | undefined | | handleWidth | Bool | Trigger onResize on width change | true | | handleHeight | Bool | Trigger onResize on height change | true | | skipOnMount | Bool | Do not trigger onResize when a component mounts | false | | refreshMode | String | Possible values: throttle and debounce See lodash docs for more information. undefined - callback will be fired for every frame | undefined | | refreshRate | Number | Use this in conjunction with refreshMode. Important! It's a numeric prop so set it accordingly, e.g. refreshRate={500} | 1000 | | refreshOptions | Object | Use this in conjunction with refreshMode. An object in shape of { leading: bool, trailing: bool }. Please refer to lodash's docs for more info | undefined | | observerOptions | Object | These options will be used as a second parameter of resizeObserver.observe method. | undefined | | targetRef | Ref | Use this prop to pass a reference to the element you want to attach resize handlers to. It must be an instance of React.useRef or React.createRef functions | undefined |

Testing with Enzyme and Jest

Thanks to @Primajin for posting this snippet

const { ResizeObserver } = window;

beforeEach(() => {
  delete window.ResizeObserver;
  window.ResizeObserver = jest.fn().mockImplementation(() => ({
    observe: jest.fn(),
    unobserve: jest.fn(),
    disconnect: jest.fn()
  }));

  wrapper = mount(<MyComponent />);
});

afterEach(() => {
  window.ResizeObserver = ResizeObserver;
  jest.restoreAllMocks();
});

it('should do my test', () => {
  // [...]
});

License

MIT

❤️

Show us some love and STAR ⭐ the project if you find it useful