Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-dnd what does $splice do

I am reading an example of the React-dnd project:

moveCard(dragIndex, hoverIndex) {
    const { cards } = this.state;
    const dragCard = cards[dragIndex];

    this.setState(update(this.state, {
      cards: {
        $splice: [
          [dragIndex, 1],
          [hoverIndex, 0, dragCard]
        ]
      }
    }));}

Is this $splice the same one explained on this page?

Could anybody explain what does this chunk of code do? The $splice function is very confusion to me.

like image 202
Cheng Avatar asked Nov 26 '15 14:11

Cheng


People also ask

What is the use of splice in React?

Definition and Usage The splice() method adds and/or removes array elements. The splice() method overwrites the original array.

How do you implement drag and drop in react with react DND?

To implement this, use the code below: import React, { useRef } from "react"; // import useDrag and useDrop hooks from react-dnd import { useDrag, useDrop } from "react-dnd"; const type = "Image"; // Need to pass which type element can be draggable, its a simple string or Symbol.


2 Answers

It's basically an immutable version of plain splice functions such as

newcards.splice(dragIndex, 1); // removing what you are dragging.
newcards.splice(hoverIndex, 0, dragCard); // inserting it into hoverIndex.

Instead of directly manipulating the target array, those Immutability Helpers are helping you update the state by creating and assigning a new state.

like image 94
goodhyun Avatar answered Oct 06 '22 05:10

goodhyun


Took me a while to understand. Here is step by step explanation in conventional arrow function

  moveCard = (dragIndex, hoverIndex) => {
    // list of cards
    let newcards = this.state.cards; 

    // dragCard is card we are dragging
    let dragCard = newcards[dragIndex]; 

   // removing this dragCard from array
    newcards.splice(dragIndex, 1);

     // insert dragCard at hover position
    newcards.splice(hoverIndex, 0, dragCard); 

    // update State
    this.setState({
      cards: newcards
    });
  };
like image 27
Hitesh Sahu Avatar answered Oct 06 '22 04:10

Hitesh Sahu