SoFunction
Updated on 2025-04-07

React drag and drop resize components

This article shares the components of React drag and drop resize for your reference. The specific content is as follows

1. Implementation process

1. UseStrengthen the package component, set absolute positioning in the package component, and add four resizable drag bars into the component. When clicking on the drag bar and dragging, the size of the DragBox will be changed, as follows:

2. Use:

<DragBox dragAble={true} minWidth={350} minHeight={184} edgeDistance={[10, 10, 10, 10]} dragCallback={} >
    {/* Use DragBox to drag the component to wrap the box that needs to be resized */}
   <div style={{ top: 100 + 'px', left: 100 + 'px', width: 350, height: 184, backgroundColor: "white" }}>
        <div style={{ backgroundColor: "yellow", width: "100%", height: 30 }}></div>
        <div style={{ backgroundColor: "green", width: "100%", height: 30 }}></div>
        <div style={{ backgroundColor: "blue", width: "100%", height: 30 }}></div>
    </div>
</DragBox>

2. Code

DragBox Components

import React, { Component, Fragment } from 'react';
import styles from "./";

/**
 * Dragged public components
 * Receive parameters:
 *       dragAble: Whether to enable drag and drop
 *     minWidth: Minimum adjustment width
 *     minHeight: Minimum adjustment height
 *       edgeDistance: Array, drag and drop the distance between the upper, lower, left and right edges of the browser in the box. If it is less than this distance, the width and height will not be adjusted again.
 *     dragCallback: drag and drop callback
 * 
  * use:
 *             Put the DragBox component that needs to be dragged and dropped, position:absolute() will be set in the DragBox component
 */
class DragBox extends Component {
    constructor(props) {
        super(props);
        // Parent component box         = ();
        // Whether to enable size modification         = false;
        // The coordinates when the mouse is pressed and save the position of the previous mouse when changing the size        , ;
        // The position when the mouse is pressed is used to represent n, s, w, and e.         = "";
        // Drag the distance between the upper, lower, left and right edges of the browser in the box. If it is less than this distance, the width and height will not be adjusted again.         = [0] || 10;
         = [1] || 10;
         = [2] || 10;
         = [3] || 10;
    }

    componentDidMount(){
        // body listens for mobile events        ('mousemove', );
        // Mouse release event        ('mouseup', );
    }

    /**
 * Clear the monitor for adjusting width and height
 */
    clearEventListener() {
        ('mousemove', );
        ('mouseup', );
    }

    componentWillUnmount() {
        ();
    }

    /**
 * End size modification when the mouse is released
 */
    up = () => {
         = false;
         = "";
    }

    /**
 * Turn on size modification when the mouse is pressed
      * @param {*} e 
 * @param {String} direction Record the identification of which box is clicked up, down, left and right
 */
    down = (e, direction) => {
         = direction;
         = true;
         = ;
         = ;
    }

    /**
 * Mouse press event Listen to the mouse movement and modify the parent section dom position
 * @param {DocumentEvent} e Event Parameters
 * @param {Boolean} changeLeft Does it need to be adjusted left
 * @param {Boolean} changeTop Does the top need to be adjusted
 * @param {Number} delta Adjust the distance difference of position
 */
    changeLeftAndTop = (event, changeLeft, changeTop, delta) => {
        let ww = ;
        let wh = ;

        if ( < 0 ||  < 0 ||  > wh ||  > ww) {
            return false;
        }
        if (changeLeft) { 
             = ( + delta, ) + 'px'; 
        }
        if (changeTop) { 
             = ( + delta, ) + 'px'; 
        }
    }

    /**
 * Mouse movement event
      * @param {*} e 
 */
    move = (e) => {
        // When the size is turned on, the div size will be modified by moving the mouse        if () {
            let finalValue;
            // The position where the mouse is pressed is in the upper part, modify the height            if ( === "top") {
                // 1.Don't modify the distance from the upper edge 10                // 2. Because modifying the height by pressing the top to modify the height, it is necessary to determine whether it is between offsetTop and (this means that it is moving upward and the mouse position is below the upper edge of the box), and the width and height of the box should not be moved or adjusted.                if ( <=  || ( <  &&   < )){ 
                     = ;
                    return; 
                }
                finalValue = (,  + ( - ));
                // Move distance. If the distance is not 0, you need to adjust the height and top                let delta =  - finalValue;
                if(delta !== 0){
                    (e, false, true, delta); 
                     = finalValue + "px";
                }
                 = ;
            } else if ( === "bottom") {// The position where the mouse is pressed is at the bottom, modify the height                // 1.Don't modify the distance from the lower edge 10                // 2. Determine whether it is moving downward and the mouse position is above the lower edge of the box. The width and height of the box should not be adjusted.                if ( -  <=  || ( +  >  &&   > )) { 
                     = ;
                    return; 
                }
                finalValue = (,  + ( - ));
                 = finalValue + "px";
                 = ;
            } else if ( === "right") { // The position where the mouse is pressed is on the right, modify the width                // 1.Don't modify the right edge 10                // 2. Determine whether it is moving to the right and the mouse position is on the left of the right edge of the box. The width and height of the box should not be adjusted.                if ( -  <=  || ( +  >  &&   > )) { 
                     = ;
                    return;
                }
                // The minimum is UI design, the maximum is 10 distance from the edge of the screen, the same as others                let value =  + ( - );
                finalValue = step(value, ,  -  - );
                 = finalValue + "px";
                 = ;
            } else if ( === "left") {// The position where the mouse is pressed is on the left, modify the width                // 1.Don't modify the left edge 10                // 2. Because the height of the top will be modified, the left and height need to be determined whether it is between offsetLeft and (this means that it is moving to the left and the mouse position is on the left edge of the box). The width and height of the box should not be moved or adjusted.                if ( <=  || ( <  &&   < )) { 
                     = ;
                    return; 
                }
                let value =  + ( - );
                finalValue = step(value, ,  -  + );
                // Move distance, if the distance is not 0, you need to adjust the width and left                let delta =  - finalValue;
                if(delta !== 0){
                    // You need to modify the position, directly modifying the width will only increase to the right                    (e, true, false, delta); 
                     = finalValue + "px";
                }
                 = ;
            }
             && (, finalValue);
        }
    }

    render() {
        // Four red boxes for moving the mouse to press and drag        const children = (
            <Fragment key={"alphaBar"}>
                <div key={1} className={} onMouseDown={(e) => (e, "top")}></div>
                <div key={2} className={} onMouseDown={(e) => (e, "bottom")}></div>
                <div key={3} className={} onMouseDown={(e) => (e, "left")}></div>
                <div key={4} className={} onMouseDown={(e) => (e, "right")}></div>
            </Fragment>
        );

        // Strengthen the children who are sent in: add position: "absolute", add four transparent boxes for dragging        const childrenProps = ;

        const cloneReactElement = (
            ,
            {
                style: {
                    // Reuse the original style                    ...,
                    // Add position:"absolute"                    position: "absolute"
                },
                ref: 
            },
            // Reuse children and add four red boxes for dragging            [, children]
        );

        return (
            <Fragment>
                {
                    cloneReactElement
                }
            </Fragment>
        );
    }
}

/**
 * Take the value between the maximum and minimum values
 * @param {*} value 
 * @param {*} min 
 * @param {*} max
 * @returns
 */
function step(value, min, max) {
    if (value < min) {
        return min;
    } else if (value > max) {
        return max;
    } else {
        return value;
    }
}

export default DragBox;

### Style of DragBox component drag bar

.alphaTopBar{
    position: absolute;
    width: 100%;
    height: 8px;
    top: -5px;
    left: 0;
    background-color: red;
    cursor: row-resize;
  }
  .alphaBottomBar{
    position: absolute;
    width: 100%;
    height: 8px;
    bottom: -5px;
    left: 0;
    background-color: red;
    cursor: row-resize;
  }
  .alphaLeftBar{
    position: absolute;
    width: 8px;
    height: 100%;
    top: 0;
    left: -5px;
    background-color: red;
    cursor: col-resize;
  }
  .alphaRightBar{
    position: absolute;
    width: 8px;
    height: 100%;
    top: 0;
    right: -5px;
    background-color: red;
    cursor: col-resize;
  }

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.