J. Rayhan
J. Rayhan

Reputation: 111

React UI not updating on state change

I have a list and need to reorder list it on clicking any item on the list. Array of string are used for binding. The function that used for reordering is returning the correct value. But the UI is not updating.

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

function swapElement(array, from, to) {
  array.splice(to, 0, array.splice(from, 1)[0])
  return array;
}

const List = props => {
  let [list, setList] = React.useState(props.item)

  const handleClick = index => {
    const items = swapElement(list, index, 0);
    console.log('UPDATED ARRAYS--------->', items)
    setList(items);
  }

  return <ul> {
    list.map((item, i) => 
      <li style={{ margin: '25px' }}
        onClick={() => handleClick(i)}
        key={i}
      >
      {item}
     </li>)
  } </ul>
}

ReactDOM.render(
  <List item={['A', 'B', 'C', 'D', 'E']} />,
  document.getElementById('root')
);

Upvotes: 5

Views: 5237

Answers (1)

Drew Reese
Drew Reese

Reputation: 202801

The UI isn't freezing, you are mutating your state object and never returning a new array object reference, so react isn't re-rendering the UI.

Shallow copy the array, then mutate new array and return.

function swapElement(array, from, to) {
  const newArray = [...array];
  newArray.splice(to, 0, newArray.splice(from, 1)[0])
  return newArray;
}

Fun fact: You can use array destructuring to swap two elements of an array. This avoids all the array element shifting that occurs with the splicing.

function swapElement(array, from, to) {
  const arr = [...array];
  [arr[from], arr[to]] = [arr[to], arr[from]];
  return arr;
}

Edit react-ui-didnt-update-array-of-string

Upvotes: 11

Related Questions