React Component Size Awareness

3.0.2 · active · verified Tue Apr 21

react-sizeme is a React library that enables components to be aware of their own rendered width and/or height, facilitating component-level responsive design. The current stable version is 3.0.2, actively maintained with recent updates including React 18 support. It differentiates itself by offering both render prop (`SizeMe`) and Higher-Order Component (`withSize`) patterns, ensuring flexibility for various component structures. It boasts performance, extensive browser support, a tiny bundle size, and compatibility with both functional and class components. The library provides configurable options for monitoring dimensions, refresh rates, and refresh modes (throttle/debounce) to optimize performance.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates both the Higher-Order Component (HOC) and Render Prop patterns for `react-sizeme`, allowing components to respond dynamically to changes in their rendered dimensions, with configurable refresh options.

import React from 'react';
import { SizeMe, SizeMeOptions } from 'react-sizeme';

interface MyComponentProps {
  title: string;
  size: { width?: number; height?: number; };
}

// Functional component using HOC
const MyHOCComponent: React.FC<MyComponentProps> = ({ title, size }) => (
  <div>
    <h2>{title} (HOC)</h2>
    <p>Width: {size.width ?? 'N/A'}px</p>
    <p>Height: {size.height ?? 'N/A'}px</p>
  </div>
);

const SizedMyHOCComponent = withSize()<{ title: string }>(MyHOCComponent);

// Functional component using Render Prop
const MyRenderPropComponent: React.FC = () => {
  const sizeMeConfig: SizeMeOptions = {
    monitorHeight: true, // Monitor height as well
    refreshRate: 50,
    refreshMode: 'debounce'
  };

  return (
    <SizeMe monitorHeight refreshRate={50} refreshMode="debounce">
      {({ size }) => (
        <div>
          <h2>My Render Prop Component</h2>
          <p>Width: {size.width ?? 'N/A'}px</p>
          <p>Height: {size.height ?? 'N/A'}px</p>
          {size.width && size.width < 400 && <p>I'm small!</p>}
          {size.width && size.width >= 400 && <p>I'm wide!</p>}
        </div>
      )}
    </SizeMe>
  );
};

export default function App() {
  return (
    <>
      <h1>react-sizeme Demo</h1>
      <div style={{ border: '1px solid #ccc', padding: '10px', marginBottom: '20px', resize: 'horizontal', overflow: 'auto', maxWidth: '100%' }}>
        <SizedMyHOCComponent title="Resizable Box 1" />
      </div>
      <div style={{ border: '1px solid #ccc', padding: '10px', resize: 'both', overflow: 'auto', maxWidth: '100%', height: '200px' }}>
        <MyRenderPropComponent />
      </div>
    </>
  );
}

view raw JSON →