paol-imi / muuri-react

The layout engine for React
https://paol-imi.github.io/muuri-react/
MIT License
359 stars 52 forks source link

limiting capacity of MuuriComponent #18

Closed shaheen-karodia closed 4 years ago

shaheen-karodia commented 4 years ago

Hi I am working on a scrabble game using your amazing library. I have used your kanban example as a starting point. I have a MuuriComponent for each scrabble square. I need to limit the number tiles per square to maximum of one. if you try and send a tile to another MuuriComponent and a tile already exists there, the tile should be returned to where it came from. the line i have added to do this in the useSend hook is if (newItems[toId].length > 0) return newItems;

export function useSend(setItems) { return useCallback(({ key, fromId, toId }) => {

fromId = fromId.toLowerCase();
toId = toId.toLowerCase();

setItems((items) => {
  const newItems = { ...items };

  if (newItems[toId].length > 0) return newItems;

  newItems[fromId] = newItems[fromId].filter((item) => item !== key);
  newItems[toId] = newItems[toId].concat(key);
  return newItems;
});

}, []); }

However I get the following error, are you able to assist? image

paol-imi commented 4 years ago

You should use a different approach to your problem. Instead of trying to undo the change, you can simply avoid the drop.

I have just released a new version of Muuri-react, and the new documentation explains how you should approach the problem.

You can then provide dragSort with a function and implement your logic, for example:

import { muuriMap } from "muuri-react";

// Custom logic.
<MuuriComponent
  groupIds={["groupId"]}
  dragSort={(item) => {
    const grids = muuriMap.getGroup("groupId");
    // Find all the grids with less than one item.
    const validGrids = grids.filter(grid => grid.getItems().length < 1);
    // Add the current grid.
    validGrids.push(item.getGrid());

    return validGrids;
  }}
/>

Let me know if you can implement it.

shaheen-karodia commented 4 years ago

Thank you very much, this worked.