How to set focus on specific html elements when navigating between pages in your Blazor app (with .NET 6)

Published on

There are good reasons to be intentional about which element on your site has focus; it makes your site much more accessible.

It’s one of those subtle details of using the web that we generally ignore or don’t consciously consider, but the simple visual cue that an element has focus is often the difference between knowing exactly where you are on a site (and what you’re doing) and feeling completely lost.

It isn’t just a visual cue either; for people using screen readers ‘focus’ is an important clue as to where they’ve just navigated (when navigating between pages), and/or what part of the site is currently active.

NOTE

Visual Cues

Typically a browser makes it obvious which element has focus by displaying said element with a box or some other, clear, indication that the item is ‘selected’.

If you’ve ever tried to complete a form on any site using just the keyboard you know how important it is to see where you currently are in the form.

But it hasn’t always easy to set this focus, especially when your users navigate between pages on your Blazor site.

Thankfully .NET 6 brings a new component and a much easier way to set focus on navigation.

If you spin up a new .NET 6 Blazor project you’ll find this in App.razor.

<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)"/>
<FocusOnNavigate RouteData="@routeData" Selector="h1"/>
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<LayoutView Layout="@typeof(MainLayout)">
<p role="alert">Sorry, there's nothing at this address.</p>
</LayoutView>
</NotFound>
</Router>

The new FocusOnNavigate component does what it sounds like it should, and sets focus on the first available h1 element when you navigate to a new page on your site.

Now the interesting thing about this is that you can’t really tell because, by default, elements such as headings

Next Up
  1. Three ways to hack your brain to notice the small details