Home > front end >  Render aria-current attribute with blazor's NavLink component
Render aria-current attribute with blazor's NavLink component

Time:11-07

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: enter image description here

CodePudding user response:

Here is my solution.

AriaNavLink.razor:

<NavLink class=@CssClass @attributes=Attributes>
  @ChildContent
</NavLink>


@inherits NavLink
@code {

  private const string _defaultActiveClass = "active";
  private Dictionary<string, object>? _attributes;

  private IReadOnlyDictionary<string, object> Attributes
  {
    get
    {
      if (_attributes != null) return _attributes;
      _attributes = AdditionalAttributes != null
        ? new Dictionary<string, object>(AdditionalAttributes)
        : new Dictionary<string, object>();
      // the trick to inferring "active" indirectly:
      var isActive = CssClass?.Split(' ', StringSplitOptions.TrimEntries).Contains(ActiveClass ?? _defaultActiveClass) ?? false;
      if (isActive)
        _attributes.Add("aria-current", "page");
      return _attributes;
    }
  }

}

Some page using bootstrap:

<li >
  <AriaNavLink href="/foo"  foo="bar">
    <i ></i>
    Foo
  </AriaNavLink>
</li>
  • Related