Navigating

✅ Similar to Blazor WebAssembly

Website navigation allows visitors to navigate between different pages, allowing them to easily move from one page to another as they continue browsing. This tutorial will cover the different types of navigation available in Blazor, including navigating by link and by code. Additionally, we will also cover how to detect navigation in Blazor.

Specifically, we will cover the following topics:

  • Types of navigation.
  • Navigating by link.
  • Navigating by code.
  • Detecting navigation.

By the end of this tutorial, you will have a strong understanding of how to navigate between pages in a Blazor application and how to detect navigation events.

You can download the example code used in this topic on GitHub.

Types of navigation

In a Blazor application, both you as the developer and the users have the ability to control which page to navigate to. Navigation by link occurs when the user clicks on a link, which takes them to a new page. On the other hand, navigation by code allows you to programmatically navigate to a specific page based on certain logic or conditions. This type of navigation is useful when you want to provide a more dynamic user experience or when you want to navigate to a page based on the results of some processing or validation.

Overall, Blazor's navigation system provides you with the flexibility to handle both user-initiated and programmatic navigation, allowing you to create a seamless and intuitive user experience.


Navigating by link

To create a link for the user to click, you have two options: the NavLink component and the <a> HTML tag.

<a> tag

The <a> HTML tag is a simple and standard way to create a link. It is useful when you want to create a basic link or when you need to customize the link's logic beyond what the NavLink component can provide. For example, you can use the <a> tag to create a link to an external website or to add custom attributes to the link.

An example of using the <a> tag to create a link in Blazor:

<a href="https://www.blazorschool.com">Visit blazorschool.com</a>

This creates a link that when clicked will navigate to "https://www.blazorschool.com" It's important to note that when using the <a> tag, you will have to handle the navigation logic yourself, unlike when you use the NavLink component, which provides built-in navigation handling.

NavLink component

The NavLink component is a useful tool when building a navigation bar. It allows you to create links that can automatically highlight the menu of the current page or relative pages without the need for additional code. This can help to provide a more intuitive user experience and make it clear to the user which page they are currently on.

For example, when using a website such as Blazor School, you may notice that when you navigate to the tutorials page, the "Learn" menu option is highlighted. This is achieved through the use of the NavLink component. By using this component, the website can automatically update the navigation bar to reflect the user's current location.

Overall, the NavLink component is a useful tool for building navigation bars in Blazor because it allows you to create links that can automatically highlight the current page or relative pages, providing a more intuitive and user-friendly experience.

blazorschool-menu.png

Creating a link with the NavLink component in Blazor requires specifying the href, which is the link's destination. The NavLink component also accepts an additional parameter ActiveClass which allows you to specify a CSS class that will be added when the link is active (i.e., the current page is the one to which the link points to), this way you can add styles to the active link.

An example of using the NavLink component to create a link:

<NavLink href="about" ActiveClass="active-link">About Us</NavLink>

This creates a link that when clicked will navigate to the About Us page and when the user is on that page, the link will have the class active-link and it will be rendered as an anchor tag <a href="about" class="active-link">About</a> in the HTML.

It's worth mentioning that the NavLink component is a part of the Blazor routing system, and it's not only an anchor tag that you can use to create a link, but also it provides an easy way to handle the active state of the link, and style it accordingly.

Overall, the NavLink component is a useful tool for creating links in Blazor, as it allows you to easily specify the destination of the link and also provides an easy way to handle the active state of the link, and style it accordingly.

Highlighting the Current Menu with NavLink

When building a navigation menu in Blazor, it is important to make it clear to the user which page they are currently on. One way to achieve this is by highlighting the current menu item in the navigation bar. The NavLink component in Blazor allows you to easily highlight the current menu item by specifying the Match parameter.

Each menu item links to a specific URL. If the browser's URL matches the menu item's URL, the link will be given a CSS class to highlight it. To determine when the browser's URL matches the link's URL, you can use the Match parameter of the NavLink component. If the Match parameter is not specified, Blazor will assume it is NavLinkMatch.Prefix.

Here's an example of using the Match parameter:

<NavLink href="about" Match="NavLinkMatch.Exact" ActiveClass="active">About Us</NavLink>

Understanding the NavLinkMatch enum

The NavLink component in Blazor uses the Match parameter to determine when to highlight a menu item. The Match parameter accepts a value from the NavLinkMatch enum, which has two possible options: Prefix and All.

When the Match parameter is set to NavLinkMatch.Prefix, a menu item will be highlighted if the browser's URL starts with the href value of the NavLink. This is the default behavior if the Match parameter is not specified.

navlinkmatch-prefix-explain.png

On the other hand, when the Match parameter is set to NavLinkMatch.All, a menu item will be highlighted only if the browser's URL is exactly the same as the href value of the NavLink. This allows for a more precise match between the browser's URL and the NavLink's href.

navlinkmatch-all-explain.png

Overall, the NavLinkMatch enum is a powerful tool for controlling the highlighting of menu items by providing the flexibility to decide whether to match the entire URL or just its prefix.

Customizing highlighting classes with NavLink

By default, when the browser's URL matches a NavLink, the link will be highlighted with the CSS class active. For example, when a link matches the browser's URL, Blazor will render the following tag:

<a href="about" class="active">About</a>

If you want to change the highlighting CSS class, you can use the ActiveClass parameter of the NavLink component. The ActiveClass parameter accepts a string of classes separated by a space, For instance, assuming you have the following NavLink tag:

<NavLink href="about" ActiveClass="highlighted-link active">About</NavLink>

This will add both highlighted-link and active classes when the link is active as follows:

<a href="about" class="highlighted-link active">About</a>

Overall, the ActiveClass parameter of the NavLink component allows you to customize the CSS class used for highlighting the active link, giving you more flexibility and control over the design of your navigation menu. You can specify multiple CSS classes separated by space, to customize it.


Navigating by code

When creating a Blazor application, there may be instances where you need to programmatically navigate to another page. To do this, you need to use the NavigationManager service. This service can be injected into your component, allowing you to use its methods to navigate to different pages.

Here's an example of how you can use the NavigationManager service to navigate to a different page:

@inject NavigationManager navManager

<button type="button" @onclick="NavigateToPage">Go to About</button>

@code {
    private void NavigateToPage()
    {
        navManager.NavigateTo("about");
    }
}

In this example, a button is added to the component, and when it's clicked, it calls the NavigateToPage method. Inside the method, the NavigateTo method of the NavigationManager service is called with the about parameter, which will navigate to the about page.

Navigating by code allows you to have more control over the flow of your application, and it can be useful in situations where you need to perform some logic before navigating to a specific page. It's important to note that, you need to make sure that the page you want to navigate to is already registered in your routing, otherwise it will not work.

Forcing a page reload

Blazor is a single-page application (SPA) framework, which means that the browser does not reload the page when users navigate through different pages. However, in some cases, you may want to force the browser to reload a specific page when the user navigates to it. This can be achieved by passing the forceReload parameter to the NavigateTo method of the NavigationManager service.

Here's an example of how you can use the forceReload parameter to reload a page:

navManager.NavigateTo("about", forceReload: true);

In this example, the NavigateTo method is called with the about parameter and the forceReload parameter set to true. This will cause the browser to reload the about page, even if the user has already visited it.

It's worth noting that, forcing a page reload can lead to a poor user experience as it will reload the whole page even though most of the content is the same, it's better to use it only when it's really needed.

Navigating without storing history

When a user navigates through a Blazor application, the browser automatically stores the previous pages in the history stack. This allows users to use the browser's back and forward buttons to navigate between pages. This is an example of history stack:

history-stack-example.png

However, in some cases, you may want to navigate to a new page without adding it to the history stack.

You can achieve this by passing the replace parameter to the NavigateTo method of the NavigationManager service. When set to true, this parameter tells the browser to replace the current page in the history stack with the new page, rather than adding it to the stack.

Here's an example of how you can use the replace parameter to navigate without adding to the history stack:

navManager.NavigateTo("about", replace: true);

In this example, the NavigateTo method is called with the "about" parameter and the replace parameter set to true. This will cause the browser to navigate to the "about" page without adding it to the history stack.

It's worth noting that, this feature can be useful when you want to navigate to a page that does not need to be accessed through the back and forward buttons, it's your choice whether you want to use it or not.


Detecting navigation

In Blazor, the NavigationManager class allows you to detect and handle changes in the browser's location. One way to do this is by listening to the LocationChange event.

Here is an example of how to listen to the LocationChange event and handle it in your code:

@inject NavigationManager navManager
@implements IDisposable

...

@code {
    protected override void OnInitialized()
    {
        navManager.LocationChanged += OnLocationChanged;
    }

    private void OnLocationChanged(object sender, LocationChangedEventArgs eventArgs)
    {
        Console.WriteLine($"Navigation detected. {eventArgs.Location}");
    }

    public void Dispose()
    {
        navManager.LocationChanged -= OnLocationChanged;
    }
}
When working with events in Blazor, it's important to remember to unsubscribe from them when you no longer need to receive notifications. Failing to do so can lead to memory leaks and other issues.
BLAZOR SCHOOL
Designed and built with care by our dedicated team, with contributions from a supportive community. We strive to provide the best learning experience for our users.
Docs licensed CC-BY-SA-4.0
Copyright © 2021-2024 Blazor School
An unhandled error has occurred. Reload 🗙