10

I have a simple array in below and I just change index of elements in array by a handler:

const [items, setItems] = useState([
    { id: 5, val: "Italy" },
    { id: 2, val: "Germany" },
    { id: 3, val: "Brazil" },
    { id: 4, val: "Canada" }
]);

My Handler:

const handlePosition = (old_index, new_index) => {
    if (new_index >= items.length) {
      var k = new_index - items.length + 1;
      while (k--) {
        items.push(undefined);
      }
    }
    items.splice(new_index, 0, items.splice(old_index, 1)[0]);

    setItems(items);

    console.log(items);
};

I try to render the items array as follows:

<ul>
  {items.map((item, index) => (
    <li key={item.id}>
      {item.val}
        <button onClick={() => handlePosition(index, index + 1)}>DOWN</button>
        <button onClick={() => handlePosition(index, index - 1)}>UP</button>
    </li>
  ))}
</ul>

Now, My array changed properly and updates the state but not re-render.

Here is a demo of my project in CodeSandBox: Link

1 Answer 1

26

It's because the instance of the items array is not changing.

Try this:

setItems([...items]);

That copies the array to a new identical array. React will see that it's different and will re-render.

Sign up to request clarification or add additional context in comments.

2 Comments

I now understand ...
My good god, the way I coded it this shouldn't in my logical sense have mattered BUT IT DID. thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.