Home > Mobile >  What is this kind of sorting called and how do I properly implement it in React
What is this kind of sorting called and how do I properly implement it in React

Time:04-05

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)}>
            <>&#x022D6;</>
          </span>)}
          {instruction.sort < instructions.length - 1 && (<span className="down" onClick={() => sortList(instruction, 'down')}>
            <>&#x022D7;</>
          </span>)}
        </div>
        {instruction.description || <h2>{instruction.grouptitle}</h2>}
      </li>
    </>
  );
}

Explanation of changes

  • Instead of two methods sortUp and sortDown one common method with a direction parameter is used
  • Using the sort prop as the index to the array, the two elements (which need to be interchanged) are identified and their sort prop updated
  • The setInstructions method is invoked using the updated array newIns

EDIT

  • The solution has been updated to conditionally render the up, down buttons (in the <span> elements).
  • Thus the top item no longer has an up button & the bottom/last item no longer has a down button.
  • Related