Currently I am working on re-implementing one of my WordPress plugins in React (Gutenberg). One of the features is re-sorting a list of input fields via a draggable UI element, this was easily implemented without React as I could move the DOM nodes around.
Now, I am rewriting everything in React and things have been going well so far. However, now I am hung up on how to shift the elements around in a sorted list by mutating its data.
Here is a mockup of what I have so far: https://stackblitz.com/edit/react-et2r6u?file=src/data.js
What I want is clicking the up arrow changes the sort
value of the selected object, then the other items in array also adjust their sort
value according, so the array items all have a sort
key that is in ascending order.
Any pointers will be helpful.
It is always preferred to provide just the relevant minimal reproducible example lines-of-code within the question.
Thanks, though, for the stackblitz link , which was helpful.
The issue was that the setInstructions
method needs to be invoked with the properly updated instructions
array.
The below code helps achieve that:
export default function InstructionLine({
index,
instruction,
instructions,
setInstructions,
}) {
function sortList(elt, direction = 'up') {
const { sort } = elt;
const newIns = [...instructions];
if (direction === 'up') {
newIns[sort] = { ...instructions[+sort - 1], sort: +sort };
newIns[+sort - 1] = { ...instructions[sort], sort: +sort - 1 };
} else {
newIns[sort] = { ...instructions[+sort + 1], sort: +sort };
newIns[+sort + 1] = { ...instructions[sort], sort: +sort + 1 };
}
console.log(newIns);
setInstructions(newIns);
}
return (
<>
<li>
<div>
{instruction.sort > 0 && (<span className="up" onClick={() => sortList(instruction)}>
<>⋖</>
</span>)}
{instruction.sort < instructions.length - 1 && (<span className="down" onClick={() => sortList(instruction, 'down')}>
<>⋗</>
</span>)}
</div>
{instruction.description || <h2>{instruction.grouptitle}</h2>}
</li>
</>
);
}
Explanation of changes
sortUp
and sortDown
one common method with a direction
parameter is usedsort
prop as the index
to the array, the two elements (which need to be interchanged) are identified and their sort
prop updatedsetInstructions
method is invoked using the updated array newIns
EDIT
up
, down
buttons (in the <span>
elements).up
button & the bottom/last item no longer has a down
button.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.