Are there any way to update w & h of react-grid-layout items?

117 Views Asked by At

I'm attempting to update the width and height of a specific grid item. I've consulted the documentation, but I couldn't find any information on achieving this specific task.

I want to avoid manually resizing the item via drag-and-drop; instead, I'd like to implement a solution where I can change the size to specific dimensions (for example, setting w: 3 and h: 1) by clicking a button.

Video

Code:

export default function BentoCards() {
  const items = [
    { i: "a", x: 0, y: 0, w: 2, h: 1 },
    { i: "b", x: 2, y: 4, w: 2, h: 1 },
  ];

  const [stateLayout, setStateLayout] = useState(items);

  const ResponsiveGridLayout = WidthProvider(Responsive);
  const gridLayoutRef = useRef<React.MutableRefObject<any>>(null);
  const gridLayouts = Array.from({ length: items.length }, () => useRef(null));

  const testChangeHProgrammatically = () => {
    setStateLayout((prevData) => {
      const newData = [...prevData]; // Create a copy of the array
      newData[0].h = 3; // Update the specific element
      return newData; // Return the updated array
    });
  };

  return (
    <>
      <ResponsiveGridLayout
        className="layout"
        breakpoints={{ sm: 768, xs: 480 }}
        cols={{ sm: 6, xs: 2 }}
        resizeHandles={["se"]}
        layouts={{ sm: stateLayout, xs: stateLayout }}
      >
        {stateLayout.map((item, index: number) => {
          console.log("re-render");
          return (
            <CustomGridItemComponent
              key={item.i}
              className="bg-red-500"
              data-grid={{ ...item }}
              ref={gridLayouts[index]}
            >
              Hello World
              <Resizable key={item.i} handleAxis="s"></Resizable>
            </CustomGridItemComponent>
          );
        })}
      </ResponsiveGridLayout>
      <button onClick={testChangeHProgrammatically}>Change Size</button>
    </>
  );
}

I've attempted a solution, but unfortunately, it causes an undesirable flicker when the component re-renders.

1

There are 1 best solutions below

0
On

I found the solution. It's not literally in the documentation, but after trying many solutions, I found the correct approach. It involves using memo for the entire grid layout, not just for the child elements

const ResponsiveReactGridLayout = useMemo(
    () => WidthProvider(Responsive),
    []
  );