C#C
C#4mo ago
Rese

@key directive switches two elements around for no apparent reason

Hello,

Is there any scenario in which using the @key directive would cause two elements to switch around? From my understanding, when using foreach and @key within, the elements should retain the order they were in the UI before. I'm using Sortable JS to move the elements around and it works just fine. But the only issue arises when moving within a single foreach, if I move the element up by two spaces, it will appear normally, but on the next Blazor re-render, the top two elements will get switched around. This issue does not happen in any other case.

So what happens:

Initial ordering:
1
2
3

After move appears correctly:
3
1
2

Blazor re-renders:
1
3
2

If I reload page, it looks how it should:
3
1
2

Any ideas?
Was this page helpful?