When a user open a web page that contains a form, they expect the first input to be focused so they can start typing. In an html page, you can use the autofocus
attribute. However, the browser only check this attribute the first time the page is loaded. This means, this is not applicable in an SPA application without pre-rendering.
The workaround is to use the focus()
function once the page is rendered to focus the desired element.
First, you need to add the following JavaScript function to your project before the blazor script:
<script>
function BlazorFocusElement(element) {
if (element instanceof HTMLElement) {
element.focus();
}
}
</script>
<script src="_framework/blazor.webassembly.js"></script>
Then, you can create an extension method to invoke this function:
using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using System.Threading.Tasks;
namespace AutoFocusBlazorApp
{
public static class JSInteropFocusExtensions
{
public static ValueTask FocusAsync(this IJSRuntime jsRuntime, ElementReference elementReference)
{
return jsRuntime.InvokeVoidAsync("BlazorFocusElement", elementReference);
}
}
}
Now, you can use this method in a Blazor component by creating a reference to an element using @ref
and using the Focus
method on it:
@page "/"
@inject IJSRuntime JSRuntime
<EditForm Model="editItem">
<input type="text" @ref="firstInput" />
<button type="submit">submit</button>
</EditForm>
@code {
private ElementReference firstInput;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
// Focus the element
await JSRuntime.FocusAsync(firstInput);
}
}
}
#blazor #.net #asp.net core #web