Dynamic number of columns with react-grid-layout

214 Views Asked by At

I would like to drag and drop items into a grid but don't want the columns to be fixed. That means that if you "drag from outside" and drop it further to the right (an area that doesn't exist yet), the grid should grow automatically.

In other words, the I would like the grid to grow horizontally in the same way it can grow vertically. Currently react-grid-layout seems to only allow dynamic rows but not dynamic columns.

Is it possible with react-grid-layout to make columns grow when dragging from outside?

1

There are 1 best solutions below

0
On

Here's an example

import React, { useState } from 'react';

function DynamicGrid() {
  const [columns, setColumns] = useState(2); //Initial number of columns

  const handleDrop = (e) => {
    const dropX = e.clientX; //X coordinate of the drop location
    const gridWidth = document.getElementById('grid-container').clientWidth;
    const newColumns = Math.ceil(dropX / (gridWidth / columns));
    setColumns(newColumns);
  };

  const items = [...]; //Your grid items

  return (
    <div id="grid-container" onDrop={handleDrop}>
      <div
        style={{ display: 'grid', gridTemplateColumns: `repeat(${columns}, 1fr)` }}
      >
        {items.map((item, index) => (
          <div key={index}>{item}</div>
        ))}
      </div>
    </div>
  );
}

export default DynamicGrid;