Blazor's NavLink
component detects whether the link refers to the current page, and sets the active
class.
It is customary to also set the aria-current="page"
attribute, when it is part of a menu.
Can the component do that somehow? Or could I wrap it in a custom component that does this?
I can't find an extension point that easily allows for this: docs, source.
Extending the existing NavLink
public class NavLinkExtended : NavLink
{
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.OpenElement(0, "a");
builder.AddMultipleAttributes(1, AdditionalAttributes);
builder.AddAttribute(2, "class", CssClass);
if(CssClass.Contains("active"))
{
builder.AddAttribute(3, "aria-current", "page");
builder.AddContent(4, ChildContent);
builder.CloseElement();
}
else
{
builder.AddContent(3, ChildContent);
builder.CloseElement();
}
}
}