Sergey Khmelevskoy
Sergey Khmelevskoy

Reputation: 2544

React sorted list - click events fired incorrectly

I have a list of services sorted based on checked/unchecked values. So unchecked goes at the top of the list and checked goes at the bottom. After saving the list, the sorting function runs again in a render function.

The sorting function is correct, however, on the second render, the behavior is very strange. When some selected and saved, selecting checkbox again behaves like those "filtered down" element are still in the list (list render is correct, but events are fired with "shift" in render)

Not sure if code example would be self-explanatory, that's why I'm attaching short gif of the problem

enter image description here

  const content = serviceContext.getList
    .sort((a, b) => {
      // show unselected at top of list
      if (activeNode !== 'DEFAULT') {
        const aChecked = serviceContext.nodeListArrayIds.includes(a.service_id);
        const bChecked = serviceContext.nodeListArrayIds.includes(b.service_id);

        return aChecked - bChecked;
      }

      return -1;
    })


List elements are keyed (uniqully)

          <tbody>
            {content &&
              content.map((row, idx) => (
                <tr key={idx}>
                  {row &&
                    row.map((col, i) => (
                      <td key={`${idx}_${i}`}>
                        <AdminListCol col={col} callback={colCallback} />
                      </td>
                    ))}
                </tr>
              ))}
          </tbody>

Upvotes: 1

Views: 92

Answers (1)

Moritz
Moritz

Reputation: 376

You shouldn't use the index of an element as a key.

Check out this blog post for more explanation.

Upvotes: 1

Related Questions