How can I implement draggable and resizable <div> elements to create resizable columns in an antd table using React?

I am currently utilizing the Reacts Antd library to showcase the contents of my table. I am interested in implementing a feature that allows me to resize the column widths. To achieve this, I have wrapped the column in my element as depicted below. The dragging functionality is working seamlessly as expected; however, an issue arises where the handleMouseUp method is only triggered upon clicking again, rather than when releasing the mouse button. In attempting to resolve this, I referred to the link provided at https://www.w3schools.com/HOWTO/howto_js_draggable.asp. Despite following the instructions, the problem persists, and I am unable to identify its cause.

Please assist me in identifying any potential issues within the code snippet provided below.

import React from 'react';
import { memo } from 'react';

const ResizeableHeaderComponent = (props: any) => {
  const onResize = (event: MouseEvent) => {
    if (event.movementX != 0) {
      event.preventDefault();
      props.onResize(event, props.index);
    }
  };

  const handleMouseUp = () => {
    window.removeEventListener('mousemove', onResize);
  };

  const handleMouseDown = () => {
    window.addEventListener('mousemove', onResize);
    window.addEventListener('mouseup', handleMouseUp);
  };
  return (
    <>
      {props.title}
      <div
        draggable={true}
        style={{
          position: 'absolute',
          bottom: 0,
          right: '-5px',
          width: '10px',
          height: '100%',
          zIndex: 5,
          cursor: 'col-resize'
        }}
        onMouseDown={handleMouseDown}
      />
    </>
  );
};

export default memo(ResizeableHeaderComponent);

Answer №1

Make sure to include both the mousemove and mouseup event listeners, and don't forget to add a function called handleMouseUp as well.

It's recommended to take out the draggable={true} attribute from the div element in order to allow resizing via the mousemove event.

import React, { memo } from 'react';

const ResizableHeaderComponent = (props: any) => {
  const onResize = (event: MouseEvent) => {
    if (event.movementX !== 0) {
      event.preventDefault();
      props.onResize(event, props.index);
    }
  };

  const handleMouseUp = () => {
    window.removeEventListener('mousemove', onResize);
    window.removeEventListener('mouseup', handleMouseUp);
  };

  const handleMouseDown = () => {
    window.addEventListener('mousemove', onResize);
    window.addEventListener('mouseup', handleMouseUp);
  };

  return (
    <>
      {props.title}
      <div
        style={{
          position: 'absolute',
          bottom: 0,
          right: '-5px',
          width: '10px',
          height: '100%',
          zIndex: 5,
          cursor: 'col-resize'
        }}
        onMouseDown={handleMouseDown}
      />
    </>
  );
};

export default memo(ResizableHeaderComponent);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the props to appear empty in a Child component within a Quasar framework and Vue 3 application?

I am facing an issue while passing props to a Child component table in my Quasar Vue3 app. The content is not being rendered, and I can't figure out why. Strangely, the console is clear of any errors. In the parent component, I am creating an object w ...

Whenever I attempt to generate a forecast utilizing a tensorflow.js model, I encounter the following error message: "Uncaught TypeError: Cannot read property 'length' of undefined."

I'm currently working on a project to build a website that utilizes a deep learning model for real-time sentiment analysis. However, I've encountered an issue when using the model.predict() function. It throws an error message: Uncaught TypeErro ...

Centering PayPal buttons horizontally with a width specified as a percentage

Take a look at this interactive coding playground showcasing the following React code: import React from "react"; import ReactDOM from "react-dom"; import { PayPalScriptProvider, PayPalButtons, usePayPalScriptReducer } from " ...

Click the button in Javascript to add new content

I am currently experimenting with JavaScript to dynamically add new content upon clicking a button. Although I have successfully implemented the JavaScript code to work when the button is clicked once, I would like it to produce a new 'hello world&ap ...

Exploring the concept of passing 'this' as a parameter in JavaScript

<button type="button" aria-haspopup="dialog" aria-controls="b" onclick="openLayer($('#b'))"> button</button> <div role="dialog" id="b"><"button type="button">close<"/button></div> function openLayer(target){ ...

Sorting problem with the ReactJS library "react-sortable-hoc"

I am currently experimenting with a sample using react-sortable-hoc, but I am facing an issue where the sortables fail to maintain the state during sorting. Check out the GIF below for reference. https://i.sstatic.net/xGm4b.gif Here is the code snippet f ...

The specified project directory was not detected. Please restart Next.js in your updated directory

I am facing a challenge with running my NextJS web app on a VPS server with PM2 as the Process Management tool. Despite trying different approaches, I am unable to get it to run properly. I have a deploy.js file that successfully deploys my other NextJS an ...

URL for Database Query String

I need help figuring out how to extract database information using a URL. On the page, each event entry should have a hyperlink that leads to a new form where administrators can record results for that specific event. The EventID is passed as a query st ...

Managing text size in HTML email designs

How can I maintain consistent font sizes in HTML EMAILS? The fonts look great on the website, but in my email they appear small and close together. Check out Live Demo I've attached a screenshot of how the email appears to me. Any suggestions on h ...

Building a responsive HTML5 site optimized for various screen sizes

I'm working on a website design that includes just one <div>. I have managed to make it responsive to different screen resolutions, but when testing it on a laptop, the horizontal and vertical scrollbars are automatically appearing. Does anyone ...

Pattern matching excluding "two or more" white spaces

Looking for a unique regular expression that meets the following criteria: No spaces allowed at the beginning or end of a line Only one space permitted between words The previous attempt using "^[АЯ-Ёа-яё0-9' ']+$" didn't q ...

Refine Image Display when Scaling Down on Screen

When I zoom in, the image area goes off-screen. I want it to stay fixed in place. <img style="margin-bottom:-10px;width:280px;height:280px;border-adius:50% ;border:3px solid white" id="image" src="@Model.Image" /> <br /> <a id="editbutto ...

One way to retrieve the step value from a slider using jQuery

I need to retrieve the step value of a slider using jQuery. While I can currently locate the step value in the HTML code, I would like to avoid having to update it manually across multiple files if it changes in the future. When I mention the step value, ...

Tips for extracting user-provided data from a dynamic table in Python with the help of Flask and JINJA2

I have been working on a Flask application where users can interact with a table by changing a cell and having those changes immediately reflected, such as updating them in the database. Check out the screenshots below: https://i.sstatic.net/3KCVP.png htt ...

Implementing Ajax calls and retrieving JSON arrays within Laravel 5

I'm just diving into the world of "AJAX" and have been experimenting with sending a request "ONSELECT" using "AJAX" in order to receive a "JSON" response in "laravel 5". Below is my View setup: <select> <option data-id="a" value="a">a< ...

Implementing Google Places reviews on a website with the help of JavaScript

Struggling to display the Google reviews for my company on our website, I can't seem to make it work. I've attempted to use this code: <script> $(function() { var people = []; $.getJSON('https://maps.googleapis.com ...

The PHP include function seems to be failing to insert my PHP file into the webpage

When attempting to include the tabnav_Browse.php page, located in the includes directory, and the Browse_Page1.php file, located in the Browse directory, by adding this code to the <?php include ("../includes/tabnav_Browse.php"); ?>, nothing is displ ...

Filtering in AngularJS based on a specific ID

Currently, I am dealing with a JSON encoded response from PHP that looks like this... [ {"ID":"149","IDusr":"4","aut_more_info":"good","doc_name":"img1838142879.jpeg","doc_type":"jpg"},{"ID":"149","IDusr":"4","aut_more_info":"good","img5733250433.jpeg","d ...

Step-by-step guide to creating a "select all" checkbox feature in AngularJS

On my HTML page, I have incorporated multiple checkboxes using AngularJs. Is there a way to add one more checkbox named "select all"? Ideally, when this checkbox is selected, all other checkboxes on the page should automatically be checked as well. Any su ...

When configuring Gatsby with Typescript, you may encounter the error message: "You cannot utilize JSX unless the '--jsx' flag is provided."

I am currently working on a Gatsby project and decided to implement Typescript into it. However, I encountered an error in my TSX files which reads: Cannot use JSX unless the '--jsx' flag is provided. What have I tried? I consulted the docume ...