using react-dnd beautiful how do I insert new item into the array, or does it not work?

Alexander Hemming

In my project I am trying to change my information into react-dnd beutiful drag and drop.

But as i changed it, the drag and drop does not work for new items inserted into the array.

How do I make it so that it works still in this example?

code sandbox: https://codesandbox.io/s/react-drag-and-drop-react-beautiful-dnd-forked-oo8nd?file=/src/index.js:0-5732

import React, { useState } from "react";
import ReactDOM from "react-dom";
import { DragDropContext, Droppable, Draggable } from "react-beautiful-dnd";

// fake data generator
const getItems = (count, offset = 0) =>
  Array.from({ length: count }, (v, k) => k).map((k) => ({
    id: `item-${k + offset}-${new Date().getTime()}`,
    content: `item ${k + offset}`
  }));

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

  return result;
};

/**
 * Moves an item from one list to another list.
 */
const move = (source, destination, droppableSource, droppableDestination) => {
  const sourceClone = Array.from(source);
  const destClone = Array.from(destination);
  const [removed] = sourceClone.splice(droppableSource.index, 1);

  destClone.splice(droppableDestination.index, 0, removed);

  const result = {};
  result[droppableSource.droppableId] = sourceClone;
  result[droppableDestination.droppableId] = destClone;

  return result;
};
const grid = 8;

const getItemStyle = (isDragging, draggableStyle) => ({
  // some basic styles to make the items look a bit nicer
  userSelect: "none",
  padding: grid * 2,
  margin: `0 0 ${grid}px 0`,

  // change background colour if dragging
  background: isDragging ? "lightgreen" : "grey",

  // styles we need to apply on draggables
  ...draggableStyle
});
const getListStyle = (isDraggingOver) => ({
  background: isDraggingOver ? "lightblue" : "lightgrey",
  padding: grid,
  width: 250
});

function QuoteApp() {
  const [state, setState] = useState([getItems(10), getItems(5, 10)]);

  function onDragEnd(result) {
    const { source, destination } = result;

    // dropped outside the list
    if (!destination) {
      return;
    }
    const sInd = +source.droppableId;
    const dInd = +destination.droppableId;

    if (sInd === dInd) {
      const items = reorder(state[sInd], source.index, destination.index);
      const newState = [...state];
      newState[sInd] = items;
      setState(newState);
    } else {
      const result = move(state[sInd], state[dInd], source, destination);
      const newState = [...state];
      newState[sInd] = result[sInd];
      newState[dInd] = result[dInd];

      setState(newState.filter((group) => group.length));
    }
  }

  return (
    <div>
      <button
        type="button"
        onClick={() => {
          setState([...state, []]);
        }}
      >
        Add new group
      </button>
      <button
        type="button"
        onClick={() => {
          setState([...state, getItems(1)]);
        }}
      >
        Add new item
      </button>
      <div style={{ display: "flex" }}>
        <DragDropContext onDragEnd={onDragEnd}>
          {state.map((el, ind) => (
            <Droppable key={ind} droppableId={`${ind}`}>
              {(provided, snapshot) => (
                <div
                  ref={provided.innerRef}
                  style={getListStyle(snapshot.isDraggingOver)}
                  {...provided.droppableProps}
                >
                  {el.map((item, index) => (
                    <Draggable
                      key={item.id}
                      draggableId={item.id}
                      index={index}
                    >
                      {(provided, snapshot) => (
                        <div
                          ref={provided.innerRef}
                          {...provided.draggableProps}
                          {...provided.dragHandleProps}
                          style={getItemStyle(
                            snapshot.isDragging,
                            provided.draggableProps.style
                          )}
                        >
                          <div
                            style={{
                              display: "flex",
                              justifyContent: "space-around"
                            }}
                          >
                            ind:{ind} , index{index} ,{item.content}
                            <button
                              type="button"
                              onClick={() => {
                                const newState = [...state];
                                newState[ind].splice(index, 1);
                                setState(
                                  newState.filter((group) => group.length)
                                );
                              }}
                            >
                              delete
                            </button>
                            <button
                              type="button"
                              onClick={() => {
                                const newState = [...state];
                                newState[ind].splice(
                                  index,
                                  0,
                                  getItems(1, index)
                                );
                                setState(
                                  newState.filter((group) => group.length)
                                );
                              }}
                            >
                              add s/o
                            </button>
                          </div>
                        </div>
                      )}
                    </Draggable>
                  ))}
                  {provided.placeholder}
                </div>
              )}
            </Droppable>
          ))}
        </DragDropContext>
      </div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<QuoteApp />, rootElement);

The specific change is the "add s/o" button

Thankyou for your time

Drew Reese

Issue

When you insert/add a "s/o" (sorry, not sure what that is) you splice in the return value from getItems which is an array, but your main state shape is an array of objects.

const getItems = (count, offset = 0) =>
  Array.from({ length: count }, (v, k) => k).map((k) => ({
    id: `item-${k + offset}-${new Date().getTime()}`,
    content: `item ${k + offset}`
  }));

...

<button
  type="button"
  onClick={() => {
    const newState = [...state];
    newState[ind].splice(
      index,
      0,
      getItems(1, index) // <-- inserts array!!
      );
    setState(
      newState.filter((group) => group.length)
    );
  }}
>
  add s/o
</button>

You've inserted an array instead of the object.

{newState: Array(2)}
  newState: Array(2)
    0: Array(11)
      0: Array(1) // <-- inserted array
        0: Object // <-- object you want inserted
          id: "item-0-1609711045911"
          content: "item 0"
      1: Object
        id: "item-0-1609711042837"
        content: "item 0"
      2: Object
      3: Object
      4: Object
      5: Object
      6: Object
      7: Object
      8: Object
      9: Object
      10: Object
    1: Array(5)

Solution

Seems a rather simple solution is to pop the single inserted object from getItems when splicing in the new "s/o".

<button
  type="button"
  onClick={() => {
    const newState = [...state];
    newState[ind].splice(
      index,
      0,
      getItems(1, index).pop(), // <-- pop value from array
      );
    setState(
      newState.filter((group) => group.length)
    );
  }}
>
  add s/o
</button>

Edit using-react-dnd-beautiful-how-do-i-insert-new-item-into-the-array-or-does-it-no

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

分類Dev

How to access this item using Beautiful Soup

分類Dev

How do I add an item to an array in a database using a PATCH request in JavaScript?

分類Dev

How do I declare a 2d array in C++ using new?

分類Dev

How do I create an array of one item in Go?

分類Dev

how do I perform a function on an item in a jquery array

分類Dev

How do I grab the text inside of a span tag in Python using Beautiful Soup

分類Dev

How does pandas argsort work? How do I interpret the result?

分類Dev

How does image transparency work and how do I implement it?

分類Dev

how to insert an item to an array that is inside an object in mongoose?

分類Dev

How do I create a new class in IntelliJ without using the mouse?

分類Dev

How do I add new lines to a Perl script using PPI?

分類Dev

How do I respond to a prompt after using & to make a new process?

分類Dev

How do I get all item of an array which doesn't exists in another array

分類Dev

How do I insert new line in EditText field while reading the text from a file

分類Dev

react-beautiful-dndでmaterial-uiテーブルを使用する

分類Dev

How do I create a react list component from an array of objects?

分類Dev

How do I map over a contacts array to produce a new array with objects and properties?

分類Dev

How to add a new Activity type to the Task work item in TFS 2018

分類Dev

How do I create JSON array using QT

分類Dev

How do I pass array information using a factory in Javascript?

分類Dev

How do I display array objects using a simple loop and 'if' statements?

分類Dev

How do I get specific JSON item?

分類Dev

How do I get the selected item in MvxLIstView

分類Dev

How to remove array item property using AngularJs

分類Dev

How do I insert column into table?

分類Dev

Using Umbraco 7.2 grid view, how do I insert the grid view into my template?

分類Dev

How do I insert a record with a RECORD field in BigQuery using DML syntax?

分類Dev

How does index of an array work in postgresql?

分類Dev

How does array declaration work in C++?

Related 関連記事

  1. 1

    How to access this item using Beautiful Soup

  2. 2

    How do I add an item to an array in a database using a PATCH request in JavaScript?

  3. 3

    How do I declare a 2d array in C++ using new?

  4. 4

    How do I create an array of one item in Go?

  5. 5

    how do I perform a function on an item in a jquery array

  6. 6

    How do I grab the text inside of a span tag in Python using Beautiful Soup

  7. 7

    How does pandas argsort work? How do I interpret the result?

  8. 8

    How does image transparency work and how do I implement it?

  9. 9

    how to insert an item to an array that is inside an object in mongoose?

  10. 10

    How do I create a new class in IntelliJ without using the mouse?

  11. 11

    How do I add new lines to a Perl script using PPI?

  12. 12

    How do I respond to a prompt after using & to make a new process?

  13. 13

    How do I get all item of an array which doesn't exists in another array

  14. 14

    How do I insert new line in EditText field while reading the text from a file

  15. 15

    react-beautiful-dndでmaterial-uiテーブルを使用する

  16. 16

    How do I create a react list component from an array of objects?

  17. 17

    How do I map over a contacts array to produce a new array with objects and properties?

  18. 18

    How to add a new Activity type to the Task work item in TFS 2018

  19. 19

    How do I create JSON array using QT

  20. 20

    How do I pass array information using a factory in Javascript?

  21. 21

    How do I display array objects using a simple loop and 'if' statements?

  22. 22

    How do I get specific JSON item?

  23. 23

    How do I get the selected item in MvxLIstView

  24. 24

    How to remove array item property using AngularJs

  25. 25

    How do I insert column into table?

  26. 26

    Using Umbraco 7.2 grid view, how do I insert the grid view into my template?

  27. 27

    How do I insert a record with a RECORD field in BigQuery using DML syntax?

  28. 28

    How does index of an array work in postgresql?

  29. 29

    How does array declaration work in C++?

ホットタグ

アーカイブ