• Stars
    star
    1,940
  • Rank 23,891 (Top 0.5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 9 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

πŸ“ Compute measurements of a React component.

πŸ“ React Measure

npm version Dependency Status

Compute measurements of React components. Uses a ResizeObserver to detect when an element's dimensions have changed.

Includes a polyfill for ResizeObserver in unsupported browsers.

Install

yarn add react-measure

npm install react-measure --save

<script src="https://unpkg.com/react-measure/dist/index.umd.js"></script>
(UMD library exposed as `ReactMeasure`)

Measure Component

Wrap any child component and calculate its client rect.

Props

client: PropTypes.bool

Adds the following to contentRect.client returned in the child function.

clientTop, clientLeft, clientWidth, and clientHeight.

offset: PropTypes.bool

Adds the following to contentRect.offset returned in the child function.

offsetTop, offsetLeft, offsetWidth, and offsetHeight.

scroll: PropTypes.bool

Adds the following to contentRect.scroll returned in the child function.

scrollTop, scrollLeft, scrollWidth, and scrollHeight.

bounds: PropTypes.bool

Uses getBoundingClientRect to calculate the element rect and add it to contentRect.bounds returned in the child function.

margin: PropTypes.bool

Uses getComputedStyle to calculate margins and add it to contentRect.margin returned in the child function.

innerRef: PropTypes.func

Use this to access the internal component ref.

onResize: PropTypes.func

Callback invoked when either element width or height have changed. Note that this will be called twice on mount to get the initial values. The first call will come from componentDidMount while the second call will come from the ResizeObserver.

children: PropTypes.func

Children must be a function. Will receive the following object shape:

  • measureRef: must be passed down to your component's ref in order to obtain a proper node to measure

  • measure: use to programmatically measure your component, calls the internal measure method in withContentRect

  • contentRect: this will contain any of the following allowed rects from above: client, offset, scroll, bounds, or margin. It will also include entry from the ResizeObserver when available.

Example

import Measure from 'react-measure'
import classNames from 'classnames'

class ItemToMeasure extends Component {
  state = {
    dimensions: {
      width: -1,
      height: -1,
    },
  }

  render() {
    const { width, height } = this.state.dimensions
    const className = classNames(width < 400 && 'small-width-modifier')

    return (
      <Measure
        bounds
        onResize={contentRect => {
          this.setState({ dimensions: contentRect.bounds })
        }}
      >
        {({ measureRef }) => (
          <div ref={measureRef} className={className}>
            I can do cool things with my dimensions now :D
            {height > 250 && (
              <div>Render responsive content based on the component size!</div>
            )}
          </div>
        )}
      </Measure>
    )
  }
}

withContentRect(types) HoC

A higher-order component that provides dimensions to the wrapped component. Accepts types, which determines what measurements are returned, similar to above. Then returns a function to pass the component you want measured.

Pass an array or single value of either client, offset, scroll, bounds, or margin to calculate and receive those measurements as the prop contentRect in your wrapped component. You can also use the measure function passed down to programmatically measure your component if you need to. And finally, remember to pass down the measureRef to the component you want measured.

Passes down the same props as the Measure child function above, measureRef, measure, and contentRect.

Fun fact, the Measure component is a thin wrapper around withContentRect. Just check the source. This means your wrapped component will accept the same props as Measure does 😊

Example

import { withContentRect } from 'react-measure'

const ItemToMeasure = withContentRect('bounds')(
  ({ measureRef, measure, contentRect }) => (
    <div ref={measureRef}>
      Some content here
      <pre>{JSON.stringify(contentRect, null, 2)}</pre>
    </div>
  )
)

Run Example

clone repo

git clone [email protected]:souporserious/react-measure.git

move into folder

cd ~/react-measure

install package dependencies

yarn

move into site folder and install local site dependencies

cd ~/site && yarn

run development mode

yarn gatsby develop

More Repositories

1

react-motion-ui-pack

Wrapper component around React Motion for easier UI transitions
JavaScript
625
star
2

react-media-player

React audio and video player.
JavaScript
470
star
3

renoun

Documentation that matches the quality of your product.
TypeScript
416
star
4

restyle

The simplest way to add CSS styles to your React components.
TypeScript
304
star
5

react-view-pager

Slider/Carousel powered by React Motion.
JavaScript
293
star
6

jsxui

The design compiler for JSX.
TypeScript
175
star
7

unicon

πŸ¦„ Wrangle SVGs from your favorite design tool.
JavaScript
169
star
8

next-remote-refresh

Enable Fast Refresh for remote data in Next.js
JavaScript
151
star
9

react-aria

Utility components to help compose React ARIA components
JavaScript
144
star
10

react-fluid-container

Graceful dynamic/variable height animation
JavaScript
133
star
11

tsxmod

Refactor code, migrate to new APIs, and better understand your codebase.
TypeScript
111
star
12

reforest

🌲 Collect ordered React render data seamlessly across the server and client.
TypeScript
79
star
13

use-item-list

A primitive React hook used to coordinate indexed collections effortlessly.
JavaScript
74
star
14

lock-scrollbars

Lock all scrollbars to prevent scrolling the page.
TypeScript
73
star
15

sketch-to-svg-json-loader

Sketch to SVG JSON loader module for webpack
JavaScript
63
star
16

documenting-systems-in-nextjs

Case study of how to build a documentation system in Next.js using TS Morph.
TypeScript
52
star
17

mdx-to-md

Convert MDX to Markdown.
TypeScript
51
star
18

next-monaco

TypeScript
45
star
19

react-paper-ripple

Paper ripple animations inspired by Google Material Design
JavaScript
31
star
20

outy

A simple way to listen for events outside of elements in 390 bytes
JavaScript
31
star
21

react-matches

Simple helper components to make responsive design easier in React.
JavaScript
29
star
22

next-dx

Enhance Next.js development with utilities for local and remote content.
TypeScript
21
star
23

react-component-query

Component queries in React
JavaScript
21
star
24

animated-ui

Components for UI animations powered by Animated
JavaScript
21
star
25

build-your-own-code-playground

A simple React code playground built in Next.js
TypeScript
20
star
26

get-node-dimensions

Get accurate element dimensions, even if it's hidden!
JavaScript
20
star
27

selectly

Build composeable select menus for React.
JavaScript
19
star
28

react-midnight

Handle dates, times, and calendars with React.
JavaScript
17
star
29

docgraph

Generate rich documentation data for TypeScript and MDX codebases.
TypeScript
17
star
30

velocitytransitiongroup

React addon component to easily use Velocity animations in React.
JavaScript
17
star
31

use-roving-index

Manage an active index that needs to be contained or wrapped.
TypeScript
16
star
32

golly

Powerful flexbox grid system built on top of glamor.
JavaScript
12
star
33

tonality

Some small functions to help build and adjust color tone palettes.
JavaScript
11
star
34

use-scroll-sync

Sync scroll positions between multiple elements.
TypeScript
10
star
35

use-ref-list

Easily manage an ordered list of refs in React.
JavaScript
8
star
36

react-motion-sortable

Sortable components powered by React Motion.
JavaScript
8
star
37

react-travel

JavaScript
8
star
38

bundling-typescript-with-esbuild-for-npm

Example of bundling TypeScript using Esbuild.
JavaScript
7
star
39

create-styled-element

Simple wrapper around glamor to create styled elements in React.
JavaScript
6
star
40

monaco-textmate-syntax-highlighting

Monaco TextMate Syntax Highlighting in Next.js
TypeScript
6
star
41

nextjs-remote-mdx-fast-refresh

Workaround to get Fast Refresh working for remote MDX content in a local directory.
JavaScript
5
star
42

next-monaco-vscode-api

Monaco Editor x Next.js
TypeScript
5
star
43

react-editable

Build flexible WYSIWYG editors with ease
JavaScript
4
star
44

react-aria-ui

Collection of ARIA compliant React components.
JavaScript
4
star
45

react-rails-theme-provider

Demo of setting up ThemeProvider with react-rails
Ruby
4
star
46

app-router-form

App Router testing.
TypeScript
4
star
47

react-drop

Drop content anywhere on the page
JavaScript
4
star
48

generate-typescript-docs-using-ts-morph

Generate docs from TypeScript using TS Morph.
TypeScript
4
star
49

get-prefix

Get browser style prefixes for Javascript.
JavaScript
4
star
50

animation-bus

Define different animation stops relative to another value.
JavaScript
4
star
51

better-library-dx-using-jsdoc-links

Example of using Babel to enrich JSDoc links with helpful links.
JavaScript
3
star
52

react-cli-example

Example showing how to bundle a CLI tool using react ink and tsup.
JavaScript
3
star
53

scroll-media

Control videos or audio based on scroll position.
JavaScript
3
star
54

preact-signals-nextjs

TypeScript
3
star
55

managing-design-systems-with-typescript

An example of how to manage Design Systems with TypeScript.
TypeScript
3
star
56

site

My personal website πŸ’€
JavaScript
3
star
57

babel-plugin-extract-export

Extract ESM exports and their dependencies using Babel.
TypeScript
3
star
58

contours

An example of generating contours from a 2D array using Rust.
TypeScript
2
star
59

style-bits

JavaScript
2
star
60

reanime

JavaScript
2
star
61

esbuild-figma-plugin

Example showing how to compile Figma plugins using Esbuild.
TypeScript
2
star
62

server-components-css

TypeScript
2
star
63

mdx-bundler-and-styled-components

TypeScript
2
star
64

origins-boilerplate

A starting place for the web. Will add config settings soon.
JavaScript
2
star
65

use-frame

Sync animation frames in React.
TypeScript
2
star
66

docs-example

TypeScript
1
star
67

extract-exports-using-ts-morph

An example of how to extract an ESM export using TS Morph.
TypeScript
1
star
68

args-flags

A simple command line argument parser for Node.
JavaScript
1
star
69

calendar-fns

Small utility functions for building calendars in JavaScript.
TypeScript
1
star
70

data-slider

A simple slider that allows data attributes to control it.
JavaScript
1
star
71

vscode-ast-explorer

TypeScript
1
star
72

next-mdx-table-bug

JavaScript
1
star
73

mdx-use-client

JavaScript
1
star