1

I am using react-beautiful-dnd to build a simple vertical drag and drop list, and the list is dynamic and expandable, but when I update the list passed to dnd component, but the dnd component is not re-rendered.

I just assume that when button clicked, the state is updated and the DND component should be re-rendered as the props changed. the problem is that state is updated, but not the dnd component.

Below is the code. Thanks in advance for the help.

App file

import { Box, Button } from "@material-ui/core";
import React, { useState } from "react";
import DND from "../components/DND";

interface AppProps {}

const App: React.FC<AppProps> = ({}) => {

  const [state, setstate] = useState([0]);
  const handleClick = () => {
    const newState = [...state];
    newState.push(state[state.length - 1] + 1);
    setstate(newState);
  };

  return (
    <Box px={2}>
      <Box>{JSON.stringify(state)}</Box>
      <DND initialIds={state} />
      <Button onClick={handleClick}>++</Button>
    </Box>
  );
};

export default App;

Drag and drop component

import { Box } from "@material-ui/core";
import React, { useState } from "react";
import { DragDropContext, Draggable, Droppable } from "react-beautiful-dnd";

const reorder = (list: number[], startIndex: number, endIndex: number) => {
  const result = Array.from(list);
  const [removed] = result.splice(startIndex, 1);
  result.splice(endIndex, 0, removed);
  return result;
};

const DND: React.FC<{}> = ({ initialIds }) => {
  const [ids, setIds] = useState(initialIds);

  const onDragEnd = (result: any) => {
    if (!result.destination) {
      return;
    }
    const newList = reorder(ids, result.source.index, result.destination.index);
    setIds(newList);
  };

  return (
    <Box>
      <DragDropContext onDragEnd={onDragEnd}>
        <Droppable droppableId="droppable">
          {(provided, snapshot) => (
            <div
              {...provided.droppableProps}
              ref={provided.innerRef}
              style={getListStyle(snapshot.isDraggingOver)}
            >
              {ids.map((id, index) => (
                <Draggable key={id} draggableId={id.toString()} index={index}>
                  {(provided, snapshot) => (
                    <div
                      ref={provided.innerRef}
                      {...provided.draggableProps}
                      {...provided.dragHandleProps}
                      style={getItemStyle(
                        snapshot.isDragging,
                        provided.draggableProps.style
                      )}
                    >
                      {id}
                    </div>
                  )}
                </Draggable>
              ))}
              {provided.placeholder}
            </div>
          )}
        </Droppable>
      </DragDropContext>
    </Box>
  );
};

export default DND;

enter image description here

Sheng Zhuang
  • 647
  • 5
  • 10

0 Answers0