How To Reference and Focus a DOM Element from Blazor Component Code-Behind

The Direcive Attribute @ref can be used to refer to a specific DOM element.

There’s also a convenience method FocusAsync for focusing an input element.

In my Blazor Markup:

    <input @ref="addNameInput" type="text" placeholder="Enter your name here" />
    <button class="btn btn-primary" @onclick="AddNameAsync">Add your name</button>

And in my code-behind:

protected ElementReference addNameInput { get; set; }
protected async Task AddNameAsync()
{
    // focus the input and return if addNameInput is empty
    if(string.IsNullOrWhiteSpace(_nameToAdd))
    {
        await addNameInput.FocusAsync();
        return;
    }
}