Patrick Wambugu
rickwag's blog

rickwag's blog

Blazor: How to actually customize NavLink's ActiveClass

Blazor: How to actually customize NavLink's ActiveClass

Patrick Wambugu's photo
Patrick Wambugu
·Nov 29, 2021·

1 min read

If you're like me, trying to learn blazor, you must have come across problems that are just not as intuitive to figure out. One of these problems is how to actually create a custom class and assign it to a NavLink while its active.

During my trials of making this work, I first tried something like this

  <NavLink href="#" ActiveClass="nav-active" Match="NavLinkMatch.All">
   Home
  </NavLink>

And then for the styling

.nav-active {
 background-color: orange;
 color: black;
 font-style: normal;
}

As you probably guessed it, this did not work. The problem was, the 'nav-active' class wasn't being registered for some reason.

So, how do we actually fix this issue. Under the hood the NavLink is actually just an anchor tag. Therefore in order to reach the 'nav-active' class now on the achor tag beneath, we need to use the '::deep' combinator.

The ::deep combinator is specific to blazor and ensures styles are applied to both the parent and the children of a component.

So, this is the modified corrected styling that will actually work.

::deep .nav-active {
 background-color: orange;
 color: black;
 font-style: normal;
}

Now, all you need to do is set the ActiveClass property of all the NavLinks to the css class you want, with the '::deep' combinator and everything will work swimmingly.

Thanks.

Cover Photo by Designecologist from Pexels

 
Share this