Ora

How do I make a div resizable react?

Published in React UI Components 4 mins read

To make a div resizable in React, the most straightforward and robust method is to utilize the Resizable component from the react-resizable package. This powerful component simplifies the process by handling all the necessary event listeners and state management required for resizing, allowing you to easily wrap any div or React component and make it interactive.

Getting Started with react-resizable

The react-resizable library provides a flexible and performant solution for creating resizable elements within your React applications.

1. Installation

First, you need to install the package and its peer dependency, react-grid-layout, which react-resizable uses internally for some utilities.

npm install react-resizable react-grid-layout
# or
yarn add react-resizable react-grid-layout

2. Basic Usage

Once installed, you can import the Resizable component and wrap your target div with it. You'll typically manage the width and height of the resizable component using React state.

import React, { useState } from 'react';
import { Resizable } from 'react-resizable';
import './react-resizable.css'; // Don't forget to import the default styles

function ResizableDivExample() {
  const [width, setWidth] = useState(200);
  const [height, setHeight] = useState(200);

  // Callback function when resizing stops
  const onResize = (event, { element, size, handle }) => {
    setWidth(size.width);
    setHeight(size.height);
  };

  return (
    <div style={{ padding: '20px' }}>
      <h2>Make Your Div Resizable</h2>
      <Resizable
        width={width}
        height={height}
        onResize={onResize}
        resizeHandles={['se']} // 'se' for South-East handle
      >
        <div
          style={{
            width: width + 'px',
            height: height + 'px',
            border: '2px dashed #3498db',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: '#ecf0f1',
            boxSizing: 'border-box', // Crucial for border not affecting size
          }}
        >
          <p>Resizable Box</p>
          <p>({width}x{height})</p>
        </div>
      </Resizable>
    </div>
  );
}

export default ResizableDivExample;

Important Note: To display the resize handles correctly, you need to include the default styles provided by react-resizable. You can find them in the node_modules/react-resizable/css/styles.css path or similar, and import them directly as shown above or copy relevant styles into your project's CSS.

Key Resizable Component Props

The Resizable component offers several props to customize its behavior.

Prop Type Description Default
width number The current width of the component. Required for controlled resizing. 0
height number The current height of the component. Required for controlled resizing. 0
onResize function Callback function fired when the component is actively being resized. noop
onResizeStart function Callback function fired when resizing begins. noop
onResizeStop function Callback function fired when resizing ends. noop
minConstraints [number, number] Minimum width and height. E.g., [50, 50] for 50x50px. [10, 10]
maxConstraints [number, number] Maximum width and height. E.g., [500, 300] for 500x300px. [Infinity, Infinity]
resizeHandles string[] An array of strings specifying which resize handles to display. ['se']
axis string Restrict resizing to a specific axis ('x', 'y', or 'both'). 'both'
draggableOpts object Options to pass to the underlying Draggable component (from react-draggable). {}
handle element A custom React component to use as the resize handle. Default handle

Customizing Resizable Divs

You can further tailor the behavior and appearance of your resizable divs:

  • Specify Resize Handles: The resizeHandles prop takes an array of strings representing the desired handles. Options include:

    • 's' (south), 'w' (west), 'e' (east), 'n' (north)
    • 'sw' (south-west), 'nw' (north-west), 'se' (south-east), 'ne' (north-east)
      This allows you to control whether the user can resize from all sides, just corners, or specific edges.
    <Resizable resizeHandles={['s', 'e', 'se']}>
      {/* ...your content */}
    </Resizable>
  • Set Minimum and Maximum Dimensions: Use minConstraints and maxConstraints to define the size limits of your resizable element. These props take an array of two numbers [minWidth, minHeight] or [maxWidth, maxHeight].

    <Resizable minConstraints={[100, 80]} maxConstraints={[600, 400]}>
      {/* ...your content */}
    </Resizable>
  • Control Resize Axis: The axis prop can restrict resizing to horizontal ('x'), vertical ('y'), or both ('both').

    <Resizable axis="x">
      {/* Resizable only horizontally */}
    </Resizable>
  • Custom Resize Handles: For a unique look, you can provide your own React component to the handle prop. This allows for complete control over the styling and content of the resize grabbers.

    const CustomHandle = React.forwardRef(({ handleAxis, ...props }, ref) => (
      <div ref={ref} {...props} style={{ /* custom styles for handle */ }}>
        <span style={{ color: 'white', fontSize: '10px' }}>{handleAxis.toUpperCase()}</span>
      </div>
    ));
    
    // ... inside your component
    <Resizable handle={<CustomHandle />} resizeHandles={['se']}>
      {/* ...your content */}
    </Resizable>

Practical Tips for Resizable Components

  • Performance: For complex components or frequent resizing, debounce or throttle state updates if onResize causes performance issues, though react-resizable is generally optimized.
  • Styling: Ensure your inner div's dimensions are explicitly set based on the width and height state variables. Use box-sizing: border-box; on your resizable content to prevent padding or borders from increasing the overall size beyond the specified width and height.
  • Accessibility: Consider adding ARIA attributes (e.g., aria-valuenow, aria-valuemin, aria-valuemax) and keyboard navigation to your custom resize handles for better accessibility.

By leveraging the Resizable component from react-resizable, you can efficiently add robust resizing functionality to any div or React component in your application, enhancing user interactivity and layout flexibility.

For more details, refer to the react-resizable NPM package.