Why is my blazor component with ElementReference and IJSRuntime.InvokeAsync inside for loop not working

You can’t use an ElementReference object before it has been assigned a reference to an element. Your component is not yet created and rendered, so no ElementReference object is available. You can only use ElementReference objects after your component has been rendered.

You can do it like this:

@inject IJSRuntime JSRuntime

@foreach (var div in divs)
{
  
    <div @ref="div.ElementReference"></div>
  
}
@code
{
    private readonly IEnumerable<Div> divs = new List<Div> { new Div{JSON="{1}" },
                                                             new Div{JSON="{2}"},
                                                             new Div{JSON="{3}"}};

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {

        if (firstRender)
        {
            @foreach (var div in divs)
            {
            await JSRuntime.InvokeVoidAsync(
               "exampleJsFunctions.jsonRenderer", div.JSON, div.ElementReference);
            
            }
     
        }
    }

    public class Div
    {
        public ElementReference ElementReference { get; set; }
        public string JSON { get; set; } 

    }

 }

Put the script at the bottom of your _Host.cshtml file…

 <script>
        window.exampleJsFunctions = {
            jsonRenderer: function (json, element) {
                element.innerText = json;
            }
        }
    </script>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top