Convert Figma logo to code with AI

souporserious logoreact-measure

📏 Compute measurements of a React component.

1,941
109
1,941
31

Top Related Projects

React components for efficiently rendering large lists and tabular data

A draggable and resizable grid layout with responsive breakpoints, for React.

Make your React Components aware of their width and height!

🖱 A resizable and draggable component for React.

Quick Overview

React-measure is a React component that provides accurate measurements of DOM elements. It allows developers to easily measure the dimensions and position of elements, and re-render components when these measurements change. This library is particularly useful for creating responsive layouts and animations based on element sizes.

Pros

  • Easy to use with a simple API
  • Provides accurate and real-time measurements
  • Supports both class and functional components
  • Offers a wide range of measurement properties (width, height, top, left, etc.)

Cons

  • May introduce performance overhead if used excessively
  • Limited documentation and examples
  • Not actively maintained (last update was in 2019)
  • Might conflict with other libraries that manipulate the DOM

Code Examples

  1. Basic usage with a functional component:
import { Measure } from 'react-measure'

const MyComponent = () => (
  <Measure>
    {({ measureRef, contentRect }) => (
      <div ref={measureRef}>
        Height: {contentRect.bounds.height}
        Width: {contentRect.bounds.width}
      </div>
    )}
  </Measure>
)
  1. Using with class components and custom bounds:
import React from 'react'
import Measure from 'react-measure'

class MyComponent extends React.Component {
  state = { dimensions: {} }

  render() {
    const { dimensions } = this.state

    return (
      <Measure
        bounds
        onResize={(contentRect) => {
          this.setState({ dimensions: contentRect.bounds })
        }}
      >
        {({ measureRef }) => (
          <div ref={measureRef}>
            {`${dimensions.width}px x ${dimensions.height}px`}
          </div>
        )}
      </Measure>
    )
  }
}
  1. Measuring specific properties:
import { Measure } from 'react-measure'

const MyComponent = () => (
  <Measure client>
    {({ measureRef, contentRect }) => (
      <div ref={measureRef}>
        Client Width: {contentRect.client.width}
        Client Height: {contentRect.client.height}
      </div>
    )}
  </Measure>
)

Getting Started

  1. Install the package:

    npm install react-measure
    
  2. Import and use in your React component:

    import { Measure } from 'react-measure'
    
    const MyComponent = () => (
      <Measure>
        {({ measureRef, contentRect }) => (
          <div ref={measureRef}>
            Width: {contentRect.bounds.width}
            Height: {contentRect.bounds.height}
          </div>
        )}
      </Measure>
    )
    
  3. Customize the measurement properties and callback as needed.

Competitor Comparisons

React components for efficiently rendering large lists and tabular data

Pros of react-virtualized

  • Offers a comprehensive suite of components for efficient rendering of large lists and tabular data
  • Provides advanced features like infinite scrolling, windowing, and cell measuring
  • Has a larger community and more frequent updates

Cons of react-virtualized

  • Steeper learning curve due to its extensive API and features
  • Larger bundle size, which may impact performance for smaller applications
  • More complex setup and configuration compared to simpler alternatives

Code Comparison

react-virtualized:

import { List } from 'react-virtualized';

<List
  width={300}
  height={300}
  rowCount={1000}
  rowHeight={20}
  rowRenderer={({ index, key, style }) => (
    <div key={key} style={style}>Row {index}</div>
  )}
/>

react-measure:

import Measure from 'react-measure';

<Measure
  bounds
  onResize={contentRect => {
    console.log(contentRect.bounds);
  }}
>
  {({ measureRef }) => <div ref={measureRef}>Measured content</div>}
</Measure>

While react-virtualized focuses on efficient rendering of large datasets, react-measure is primarily used for measuring DOM elements. react-virtualized is more suitable for complex list rendering scenarios, while react-measure is a simpler tool for obtaining element dimensions and positions.

A draggable and resizable grid layout with responsive breakpoints, for React.

Pros of react-grid-layout

  • Provides a complete grid system with dragging and resizing capabilities
  • Offers responsive breakpoints for different screen sizes
  • Includes built-in collision detection and prevention

Cons of react-grid-layout

  • More complex setup and configuration required
  • Heavier package size due to additional features
  • May be overkill for simple layout needs

Code Comparison

react-grid-layout:

import GridLayout from 'react-grid-layout';

<GridLayout
  className="layout"
  layout={layout}
  cols={12}
  rowHeight={30}
  width={1200}
>
  {children}
</GridLayout>

react-measure:

import Measure from 'react-measure';

<Measure
  bounds
  onResize={contentRect => {
    this.setState({ dimensions: contentRect.bounds })
  }}
>
  {({ measureRef }) => (
    <div ref={measureRef}>
      {children}
    </div>
  )}
</Measure>

react-grid-layout is a comprehensive solution for creating dynamic, resizable grid layouts, while react-measure focuses on measuring DOM elements and providing dimension information. react-grid-layout is better suited for complex grid-based layouts, whereas react-measure is more flexible and can be used in various scenarios where element dimensions are needed.

Make your React Components aware of their width and height!

Pros of react-sizeme

  • Offers a simpler API with fewer configuration options, making it easier to use for basic sizing needs
  • Provides a higher-order component (HOC) approach, which can be more familiar to some developers
  • Supports server-side rendering out of the box

Cons of react-sizeme

  • Less flexible compared to react-measure in terms of customization options
  • May have slightly higher performance overhead due to its implementation approach
  • Limited to measuring only width and height, while react-measure offers more measurement properties

Code Comparison

react-sizeme:

import { withSize } from 'react-sizeme'

const MyComponent = ({ size }) => (
  <div>Width: {size.width}, Height: {size.height}</div>
)

export default withSize()(MyComponent)

react-measure:

import Measure from 'react-measure'

const MyComponent = () => (
  <Measure>
    {({ measureRef, contentRect }) => (
      <div ref={measureRef}>
        Width: {contentRect.entry.width}, Height: {contentRect.entry.height}
      </div>
    )}
  </Measure>
)

Both libraries serve the purpose of measuring React components, but they differ in their implementation and API design. react-sizeme offers a simpler approach with its HOC, while react-measure provides more flexibility and measurement options through its render prop pattern.

🖱 A resizable and draggable component for React.

Pros of react-rnd

  • Provides both resizing and dragging functionality out of the box
  • Offers more customization options for handles and boundaries
  • Supports touch events for mobile devices

Cons of react-rnd

  • Larger bundle size due to additional features
  • May have a steeper learning curve for simple measurement tasks
  • Less focused on pure dimension measurement

Code Comparison

react-rnd:

<Rnd
  size={{ width: 200, height: 200 }}
  position={{ x: 0, y: 0 }}
  onDragStop={(e, d) => { console.log(d.x, d.y); }}
  onResizeStop={(e, direction, ref, delta, position) => {
    console.log(ref.style.width, ref.style.height);
  }}
>
  Resizable and draggable content
</Rnd>

react-measure:

<Measure
  bounds
  onResize={contentRect => {
    console.log(contentRect.bounds);
  }}
>
  {({ measureRef }) => (
    <div ref={measureRef}>
      Measured content
    </div>
  )}
</Measure>

react-rnd is more suitable for interactive UI elements that require both resizing and dragging, while react-measure focuses on dimension measurement and is lighter-weight. Choose based on your specific requirements and performance considerations.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

📏 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 git@github.com: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

NPM DownloadsLast 30 Days