Home > front end >  Changing the list of items doesn't rerender the component when using react-beautiful-dnd
Changing the list of items doesn't rerender the component when using react-beautiful-dnd

Time:03-10

I'm using react-beautiful-dnd to let the user choose the options using drag and drop.

However, the component doesn't seem to rerender when the order of the options is changed. (I've tried console logging it, and it appears to have changed)

This is the onDragEnd method:

const onDragEnd = (result) => {
    if (!result.destination) return;

    const { source, destination } = result;

    if (!destination) {
      return;
    }

    if (source.index === destination.index) {
      return;
    }

    let items = [...list];
    const [removed] = items.splice(source.index, 1);
    items.splice(destination.index, 0, removed);

    setList([...items]);
  };

All the code can be found here in this codesandbox.

CodePudding user response:

You are rendering optionalCourses in the DND but u are updating the list state. You should render the "list" instead

return (
    <div className={componentClassName}>
      <span className={`${componentClassName}__title`}>{groupTitle}</span>
      <DragDropContext onDragEnd={onDragEnd}>
        <Droppable droppableId={groupId}>
          {(provided, snapshot) => (
            <div
              {...provided.droppableProps}
              ref={provided.innerRef}
              className={`${componentClassName}__list`}
            >
              

>  {list.map((optionalCourse, index) => {
>                      return <OptionalCourseCard key={index} {...optionalCourse} />;

              })}
              {provided.placeholder}
            </div>
          )}
        </Droppable>
      </DragDropContext>
    </div>
  );
  • Related