I went through the docs of Blazor @key
usage. But I am not sure if it works correctly in one specific case that wasn't mentioned there.
What happens if instead of this code in Page.razor
:
<div>
@foreach (var person in people)
{
<Details @key="person" Person="@person" />
}
</div>
I would place the @key
inside the Details
component itself. So for Details.razor
it would look like:
<div @key=@Person>
@* The rest of the component UI *@
</div>
@code{
[Parameter] public required Person Person { get; set; }
}
because that way when I loop this component in multiple pages I dont have to always specify the @key
parameter in the foreach. But does the blazor take it as the same/different scope ?
I don't think there's a way to do this. As the document said, the @key
should be added to the same level such as
<div @key=person1>
<div @key=person2>
...
But when you put this in a child component. You actually wrap them like:
<Details>
<div @key=person1>
</Details>
<Details>
<div @key=person2>
</Details>
The @key
scopes are isolated by each "details" so wouldn't work as you expected. The document also mentioned
Keys are local to each container element or component. Keys aren't compared globally across the document.