Resize an element using React

Let's assume that you want to create a resizable element by dragging the border of it horizontally. As an example, we'll create a resizable box of initial height: 200px and width: 200px.

At first, we'll create a block containing 2 elements:

  1. Resizable element
  2. Draggable element
jsx
import React from 'react';

const ResizableDiv = () => {
    
    return(
        <div className = 'Block'>
            <div id = 'Resizable'/>
            <div id = 'Draggable' draggable = 'true'/>
        </div>
    );
    
}

export default ResizableDiv;

And the CSS:

CSS
.Block{
    display: flex;
    align-items: center;
}
#Resizable{
    border: 1px solid black; 
    height: 200px;
    width: 200px;
}
#Draggable{
    background: rgba(1, 1, 1, 0.2);
    border-bottom: 1px solid black;
    border-right: 1px solid black;
    border-top: 1px solid black;
    cursor: col-resize;
    height: 20px;
    width: 10px;
}

Now, we'll create 2 functions:

  1. initial(): gets the initial position and size of the element.
  2. resize(): gets the final position of the element and resizes it accordingly.
jsx
import React, { useState } from 'react';

const ResizableDiv = () => {
    
    const [initialPos,   setInitialPos] = useState(null);
    const [initialSize, setInitialSize] = useState(null);
  
    const initial = (e) => {
        
        let resizable = document.getElementById('Resizable');
        
        setInitialPos(e.clientX);
        setInitialSize(resizable.offsetWidth);
        
    }
    
    const resize = (e) => {
        
        let resizable = document.getElementById('Resizable');
      
        resizable.style.width = `${parseInt(initialSize) + parseInt(e.clientX - initialPos)}px`;
      
    }
    
    return(
        <div className = 'Block'>
            <div id = 'Resizable'/>
            <div id = 'Draggable'
                draggable   = 'true'
                onDragStart = {initial} 
                onDrag      = {resize}
            />
        </div>
    );
    
}

export default ResizableDiv;

You can see a live example at CodePen.

Hi, I'm Erik, an engineer from Barcelona. If you like the post or have any comments, say hi.