How to set the focus to an InputText element?

In .NET5 it will be much simpler:

<button @onclick="() => textInput.FocusAsync()">Set focus</button>
<input @ref="textInput"/>
@code {
    ElementReference textInput;
}

NOTE: this feature was introduced in .NET5 Preview 8 so might change until the final release!

Also worth mentioning that in .NET5 RC1 JavaScript isolation was introduced via JS Module export/import. So if you still need to use JS interop do not pollute window object.

Update: .NET 5 was released and this feature works unchanged.

Also I have a cool Nuget package which can do some convenient JS tricks for you e.g.: focusing previously active element without having a @ref to it. See docs here.


You can add id parameter to your InputText and modify your Focus method and JavaScript code.

public async Task Focus(string elementId)
{
    await JSRuntime.InvokeVoidAsync("exampleJsFunctions.focusElement", elementId);
}
focusElement: function (id) {
    const element = document.getElementById(id); 
    element.focus();
}

Note: this is more a workaround than a proper solution, but Blazor doesn't seem to support it directly.