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.
Definition and Usage The splice() method adds and/or removes array elements. The splice() method overwrites the original array.
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.
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.
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
});
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With