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.
CodePudding user response:
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
- Instead of two methods
sortUpandsortDownone common method with adirectionparameter is used - Using the
sortprop as theindexto the array, the two elements (which need to be interchanged) are identified and theirsortprop updated - The
setInstructionsmethod is invoked using the updated arraynewIns
EDIT
- The solution has been updated to conditionally render the
up,downbuttons (in the<span>elements). - Thus the top item no longer has an
upbutton & the bottom/last item no longer has adownbutton.
