Skip to content

Instantly share code, notes, and snippets.

@SQL-MisterMagoo
Created December 29, 2019 00:33
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SQL-MisterMagoo/b58ed248ca4ce33a5cffbdbfa25478b1 to your computer and use it in GitHub Desktop.
Save SQL-MisterMagoo/b58ed248ca4ce33a5cffbdbfa25478b1 to your computer and use it in GitHub Desktop.
Sample code to handle deep links to anchors in Blazor components
@* 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>
@SQL-MisterMagoo
Copy link
Author

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 anchor trends once the page dashboard has loaded.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment