How to focus text box in Blazor project

If you have to spend a lot of your time in your day doing repetitive tasks such as entering data into forms then you will likely agree that it can be quite convenient to focus on a textbox in a form.

When you’re accessing a form over and over filling out the same field it can be a huge time saver to have the cursor already in the box ready for you to type and hit enter.

It can greatly reduce the stress of repetitive task by not having to use the mouse as much.

According to the Microsoft training portal, you can easily accomplish this convenient feature in a Blazor project.

All you have to do is add a reference to the input element, then a line of code to activate it. Here is a summary of the information I learned in the Microsoft Training Portal.

  1. The Blazor directive @ref="formInputName" lets the code block create an ElementReference to reference the input element. You can then use this element reference to call FocusAsync after a page has been rendered.
  2. Add code to call FocusAsync after a page has loaded
<input @ref="formInputName" @bind="MyForm.formInputName" />

Now add a variable to activate and use that reference, and the code to call FocusAsync after a page has loaded:

private ElementReference formInputName;

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender) {
        await formInputName.FocusAsync();
    }
}
Form with a text box focused by the Blazor FocusAsync().
Screenshot taken from the results of taking a Microsoft Training.