Created
December 29, 2019 00:33
-
-
Save SQL-MisterMagoo/b58ed248ca4ce33a5cffbdbfa25478b1 to your computer and use it in GitHub Desktop.
Sample code to handle deep links to anchors in Blazor components
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@* Code below handles deep links to anchors through the entire application *@ | |
@inject NavigationManager NavMan | |
@inject IJSRuntime JS | |
@code | |
{ | |
protected override async Task OnAfterRenderAsync(bool firstRender) | |
{ | |
if (firstRender && NavMan.Uri.Contains('#')) | |
{ | |
var parts = NavMan.Uri.Split('#'); | |
if (parts.Length > 1) | |
{ | |
await JS.InvokeVoidAsync("eval",$"window.location.hash='#{parts.Last()}'"); | |
} | |
} | |
} | |
} | |
@* Code below is the out-of-the-box routing *@ | |
<Router AppAssembly="typeof(BlazorTwins311.Core.Components.App).Assembly"> | |
<Found Context="routeData"> | |
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" /> | |
</Found> | |
<NotFound> | |
<LayoutView Layout="@typeof(MainLayout)"> | |
<p>Sorry, there's nothing at this address.</p> | |
</LayoutView> | |
</NotFound> | |
</Router> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The code shown above allows deep linking to a Blazor application.
For example, a user could navigate to
https://my.site/dashboard#trends
and this code ensures the browser will perform the required navigation to the anchortrends
once the pagedashboard
has loaded.