Skip to content
Proyek

Tentang

React hook for determining the size of a component

Pengembangan web dan aplikasi

Cara angka ini diukur

Pertumbuhan bintang terukur

dalam 24 jam
0
dalam 7 hari
0
dalam 15 hari
0
dalam 1 bulan
Mengumpulkan riwayat

Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.

README.md

Asli

@rehooks/component-size

Install

yarn add @rehooks/component-size

Usage

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

function MyComponent() {
  let ref = useRef(null)
  let size = useComponentSize(ref)
  // 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

Resize Observer is the API is used to determine if an element is resized. Browser support is pretty good in Chrome, but is still missing support in other major browsers.

Can i use ResizeObserver?

Polyfill

You can import the polyfill directly from here

yarn add resize-observer-polyfill

Then import it in your app:

import 'resize-observer-polyfill'

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:

loadPolyfills()
  .then(() => /* Render React application now that your Polyfills are ready */)

/**
* Do feature detection, to figure out which polyfills needs to be imported.
**/
function loadPolyfills() {
  const polyfills = []

  if (!supportsResizeObserver()) {
    polyfills.push(import('resize-observer-polyfill'))
  }

  return Promise.all(polyfills)
}

function supportsResizeObserver() {
  return (
    'ResizeObserver' in global &&
    'ResizeObserverEntry' in global &&
    'contentRect' in ResizeObserverEntry.prototype
  )
}

Jelajahi proyek terkait

Memuat…