Blazor - How to manager @ref for initial invisible part of a component

Viewed 366

I have a Blazor component who is composed of one div included in an @if directive (IsVisible). The div has an @ref. When the component is rendered, IsVisible is false. My component has a method (Show()) who set IsVisible to true and use the reference to the div. But the reference is always null (no Context and no Id).

@if (IsVisible)
{
  <div @ref="MyRef">Bla bla bla</div>
}

@code {
  bool IsVisible = false;
  ElementReference MyRef;
  public void Show()
  {
    IsVisible = true;
    StateHasChanged();
    // here, MyRef has no Context and no Id
  }
}
1 Answers

An example of the classic component misconception: StateHasChanged re-renders the component. NO, it queues a render event onto the Renderer's Queue. In your code this doesn't happen until the end of Show - it's a synchronous block of code, so runs to completion before the Renderer gets any thread time. You are checking for MyRef before it exists.

You need to modify Show.

    public async Task Show()
    {
        IsVisible = true;
        StateHasChanged();
        // Yields and lets the Renderer service it's queue
        await Task.Yield();
        // or await Task.Delay(1);
        // now we exist
        var x = MyRef;
  }
Related