🔍 What is routing in Blazor?
Routing allows your application to respond to different URLs and display specific content for each. In Blazor, this is done using the @page directive and NavLink components.
📄 How it works
In Blazor, every component that needs to be accessible via a URL must start with an @page directive.
Example:
@page "/about"
<h3>About the application</h3>
<p>This is an about page for the application.</p>
This component will be displayed when the user accesses https://site-ul-tau/about.
🧭 Navigation with
NavLink
Blazor provides the NavLink component, which works like a hyperlink but automatically adds an active CSS class when the URL is active.
<NavLink href="/" Match="NavLinkMatch.All">
Home
</NavLink>
<NavLink href="/about">
About
</NavLink>
🔎 Match="NavLinkMatch.All" means the link will be active only when the URL is exact.
📌 URL Parameters
Blazor allows passing data in the URL as parameters.
Example:
@page "/profile/{username}"
<h3>User profile: @username</h3>
@code {
[Parameter]
public string? username { get; set; }
}
Navigating to /profile/ludo, the page will display “User profile: ludo”.
🧪 Complete example: Home / About / Contact
-
Pages/Home.razor
@page "/"
<h3>Home</h3>
<p>Welcome to our Blazor application!</p>
-
Pages/About.razor
@page "/about"
<h3>About</h3>
<p>Information about the application and author.</p>
-
Pages/Contact.razor
@page "/contact"
<h3>Contact</h3>
<p>Send us a message!</p>
-
NavMenu.razor
<NavLink href="/" Match="NavLinkMatch.All">Home</NavLink>
<NavLink href="/about">About</NavLink>
<NavLink href="/contact">Contact</NavLink>
🏁 Conclusion
Navigation is an essential part of a web application. Blazor makes routing intuitive, declarative, and powerful through @page, NavLink, and URL parameters. In the next article, we will create reusable components and learn how to pass data between them using @Parameter.