Home > Net >  Move items up in a list with click with reactjs
Move items up in a list with click with reactjs

Time:09-22

I need to move the items on the list up when they are click. I have tried updating the state but it didn't work.

import React from "react";
import ReactDOM from "react-dom";

// props is an array of items

const List = (props) => {
 
  // Move the items up when they are clicked
  const { items } = props;
  const [index, setIndex] = React.useState(0);

  const handleChange = (index) => {
    // move the item up after it is clicked
    setIndex(index   1);
  };
  return (
    <ul>
      {items.map((item, index) => (
        <li key={index} onClick={() => handleChange(index)}>
          {item}
        </li>
      ))}
    </ul>
  );
};

CodePudding user response:

Your code has very big issue. const [index(1), setIndex] = React.useState(0);

items.map((item, index(2))

These two index are different. Maybe you think if you change index(1), the index(2) will be change. But it's not true.

The index(1) is different index(2). So if you call setIndex(), the component will rerender but the index(2) won't be effect.

To do that, you must reorder item array on handleChange.

CodePudding user response:

Just try this approach. First create items state that will hold the data.

const [index, setIndex] = useState(data);

Next create a handleChange function where you pass the clicked id.

const handleChange = (id) => {
  ...
}

Inside the function, we declare the first item that the value will be assigned during filtration later.

And then define a filter function where we get the first item by its id, put it inside an array, and assign it to the firstItem variable. The filter iteration process should result in filteredItems (exclude the clicked item).

Then, clone both firstItem and filteredItems by using shallow copy, set as index by using setIndex setter.

 const handleChange = (id) => {
    let firstItem;
    const filteredItems = items.filter((item) => {
      if (item.id === id) {
        firstItem = [item];
        return false;
      }
      return true;
    });
    setIndex([...firstItem, ...filteredItems]);
  };

Then, we can render it like this:

 <ul>
    {items.map((item,index) => (
      <li key={index} onClick={() => handleChange(item.id)}>
        {index.letter}
      </li>
     ))}
 </ul>
  • Related