๐—–๐—ฎ๐—น๐—น ๐——๐—ข๐—  ๐— ๐—ฒ๐˜๐—ต๐—ผ๐—ฑ๐˜€ ๐—ถ๐—ป ๐—•๐—น๐—ฎ๐˜‡๐—ผ๐—ฟ ๐—ช๐—ถ๐˜๐—ต๐—ผ๐˜‚๐˜ ๐—๐—ฆ ๐—™๐—ถ๐—น๐—ฒ๐˜€

Blazor developers often face a hurdle. You want to call a DOM method like scrollIntoView or select. Usually, this requires an external JavaScript file. You must create the file, write the function, and import it. This breaks your workflow.

The ASP.NET Core team avoids this feature to protect Blazor abstraction and performance. They want you to avoid direct DOM manipulation.

You can bypass this friction using a simple trick.

You can convert an ElementReference into an IJSObjectReference. This allows you to call DOM methods directly inside your .razor file.

How it works: The browser has a built-in Object() function. This function returns the object you pass to it. You can use this to turn an ElementReference into a usable JavaScript object on the Blazor side.

Here is the implementation:

@inject IJSRuntime JSRuntime

<input type="text" @ref="_inputElement">

@code { private ElementReference _inputElement;

private async Task ScrollIntoView()
{
    // Convert ElementReference to IJSObjectReference
    await using var inputJsObj = await JSRuntime.InvokeAsync<IJSObjectReference>("Object", _inputElement);

    // Call the DOM method directly
    await inputJsObj.InvokeVoidAsync("scrollIntoView", new { behavior = "smooth" });
}

}

Benefits:

Risks to consider:

Use this technique for small, occasional DOM tasks. Do not use it in high-frequency loops or performance-critical code.

Source: https://dev.to/j_sakamoto/opening-pandoras-box-how-to-unlock-direct-dom-method-calls-in-blazor-no-external-js-file-needed-5h5p