skip to Main Content

I have this react code:

import React, { useState } from 'react';

const App = () => {
  const [selectedSquare, setSelectedSquare] = useState(null);

  const handleSquareClick = (squareIndex) => {
    setSelectedSquare(squareIndex);
  };

  return (
    <div>
      <style>
        {`
        .square-row {
          display: flex;
        }
        
        .square {
          width: 100px;
          height: 100px;
          background-color: #ccc;
          margin-right: 10px;
          cursor: pointer;
        }
        
        .selected {
          background-color: orange;
        }
        `}
      </style>
      <div className="square-row">
        <div
          className={`square ${selectedSquare === 1 ? 'selected' : ''}`}
          onClick={() => handleSquareClick(1)}
        ></div>
        <div
          className={`square ${selectedSquare === 2 ? 'selected' : ''}`}
          onClick={() => handleSquareClick(2)}
        ></div>
        <div
          className={`square ${selectedSquare === 3 ? 'selected' : ''}`}
          onClick={() => handleSquareClick(3)}
        ></div>
      </div>
      <div className="square-row">
        <div
          className={`square ${selectedSquare === 4 ? 'selected' : ''}`}
          onClick={() => handleSquareClick(4)}
        ></div>
        <div
          className={`square ${selectedSquare === 5 ? 'selected' : ''}`}
          onClick={() => handleSquareClick(5)}
        ></div>
        <div
          className={`square ${selectedSquare === 6 ? 'selected' : ''}`}
          onClick={() => handleSquareClick(6)}
        ></div>
      </div>
    </div>
  );
};

export default App;

This simulates 6 squares if I click one of them the color changes. I want to know if there’s a way I could drag my mouse throughout the area and select multiple of them at the same time, like selecting a bunch of files from the file explorer, but in react.

2

Answers


  1. This is a complex feature to create from scratch, I recommend a library like https://dragselect.com.

    Login or Signup to reply.
  2. If you want to do it from scratch, you basically need to do the following:

    • Listen for the onMouseMove event on the document and start tracking the mouse coordinates
    • Listen for the onMouseDown event on the body or container element
    • When the onMouseDown event fires, create a div at the mouse location (position fixed)
    • When the onMouseMove event fires, change the width/height of the div to create the "selecting" effect. Also, here you check for "collision" with your divs to decide whether or not they should be marked as selected. This on its own can be a bit tricky to implement from scratch.

    Alternatively, just use an existing lib like this one https://github.com/unclecheese/react-selectable

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search