Search code examples
reactjsmaterial-uireact-beautiful-dnd

React beautiful drag and drop doesn't work with Material UI component


I've tried to make a horizontal list of MUI buttons draggable with react beautiful drag and drop. But it doesn't seem to be working.

I wrapped up my buttons with <DragDropContext>, <Droppable>,and <Draggable> tags. Here's the code.

<DragDropContext>
  <Droppable droppableId="characters">
    {(provided, snapshot) => (
    <Stack
      direction="row"
      spacing="{1}"
      className="characters"
      {...provided.droppableProps}
      ref="{provided.innerRef}"
    >
      {[1, 2, 3, 4, 5, 6, 7, 8, 9].map((x, index) => (
      <Draggable key="{x}" draggableId="{x}" index="{index}">
        {(provided, snapshot) => (
        <button
          variant="contained"
          ref="{provided.innerRef}"
          {...provided.draggableProps}
          {...provided.dragHandleProps}
        >
          {x}
        </button>
        )}
      </Draggable>
      ))}
    </Stack>
    )}
  </Droppable>
</DragDropContext>

https://drive.google.com/file/d/1VprPiCk-we5HVhvYzPPBEFdeHMX39BXC/view?usp=sharing

This is the result I've got. [Undraggable list of buttons]


Solution

  • You can see in this issue, Buttons cannot be used as custom drag handles

    So in your case, you have to put a div outside buttons. And also, draggableId should be string.

    <DragDropContext>
      <Droppable droppableId="characters">
        {(provided, snapshot) => (
          <Stack
            direction="row"
            spacing={1}
            className="characters"
            {...provided.droppableProps}
            ref={provided.innerRef}
          >
            {[1, 2, 3, 4, 5, 6, 7, 8].map((x, index) => (
              <Draggable key={x} draggableId={`${x}`} index={index}>
                {(provided, snapshot) => (
                  <div
                    ref={provided.innerRef}
                    {...provided.draggableProps}
                    {...provided.dragHandleProps}
                  >
                    <button variant="contained">{x}</button>
                  </div>
                )}
              </Draggable>
            ))}
          </Stack>
        )}
      </Droppable>
    </DragDropContext>;