๐๐ฎ๐น๐น ๐๐ข๐ ๐ ๐ฒ๐๐ต๐ผ๐ฑ๐ ๐ถ๐ป ๐๐น๐ฎ๐๐ผ๐ฟ ๐ช๐ถ๐๐ต๐ผ๐๐ ๐๐ฆ ๐๐ถ๐น๐ฒ๐
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:
- You stay inside your .razor file.
- You do not need to manage extra .js files.
- Small tasks become much faster to write.
Risks to consider:
- It requires one extra interop call.
- You must dispose of the IJSObjectReference to prevent memory leaks.
- The reference might point to a detached element if a re-render occurs.
- Overuse can lead to performance issues.
Use this technique for small, occasional DOM tasks. Do not use it in high-frequency loops or performance-critical code.