GithubHelp home page GithubHelp logo

osdiab / component-size Goto Github PK

View Code? Open in Web Editor NEW

This project forked from rehooks/component-size

0.0 1.0 0.0 147 KB

React hook for determining the size of a component

License: MIT License

HTML 12.77% JavaScript 87.23%

component-size's Introduction

@rehooks/component-size

Install

yarn add @rehooks/component-size

Usage

import { useRef, useState } from 'react'
import useComponentSize from '@rehooks/component-size'

function MyComponent() {
  const [imgElem, setImageElem] = useState(null);
  // callback ref to ensure re-render when ref is set, as per React docs
  // https://reactjs.org/docs/hooks-faq.html#how-can-i-measure-a-dom-node
  let ref = useCallback(elem => {
    if (elem !== null) {
      setImgElem(elem)
    }
  }, [])
  let size = useComponentSize(imgElem)
  // size == { width: 100, height: 200 }
  let { width, height } = size
  let imgUrl = `https://via.placeholder.com/${width}x${height}`

  return (
    <div style={{ width: '100%', height: '100%' }}>
      <img ref={ref} src={imgUrl} />
    </div>
  )
}

ResizeObserver

If it is present, this library uses the recent ResizeObserver browser API to determine if an element's content size has changed.

If a browser does not have the ResizeObserver API present, then this library falls back to listening on window size changes, which is less efficient and does not listen for changes to the component's size due to other factors like content changes. If it is not present, you can use pass a ResizeObserver implementation into the useComponentSize() hook (see below).

Browser support is pretty good in Chrome, but is still missing support in other major browsers.

Can i use ResizeObserver?

Polyfill

You can import a ResizeObserver ponyfill with this NPM library:

yarn add resize-observer-polyfill

Then use it with the useComponentSize() hook:

import ResizeObserver from 'resize-observer-polyfill'
// ...
useComponentSize(ref, { ResizeObserver });

If you are using Webpack (or similar) you could use dynamic imports, to load the Polyfill only if needed. A basic implementation could look something like this:

function getResizeObserver() {
  if (
    'ResizeObserver' in global &&
    'ResizeObserverEntry' in global &&
    'contentRect' in ResizeObserverEntry.prototype
  ) {
    return Promise.resolve(ResizeObserver);
  }
  return import('resize-observer-polyfill');
}

And in your component:

const [ResizeObserverApi, setResizeObserverApi] = setState();
useEffect(() => {
  let cancelled = false;
  getResizeObserver().then(observer => {
    if (!cancelled) {
      setResizeObserverApi(observer);
    }
  });
  return () => {
    cancelled = true;
  }
}, []);
useComponentSize(ref, { ResizeObserver: ResizeObserverApi });

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.