asp.net-coreblazorblazor-server-side.net-7.0blazor-state-management

Blazor component state and render clarity


I have a razor page with:

@page "/filemanager"
<FolderComponent/>

And in the FolderComponent.razor I have

<p2> some stuff </p2>
<MyModalComponent @ref="modalref"/>

And MyModalComponent.razor looks like :

@if (showModal)
{ 
   <h1>Modal Body</h1>
}

@code{
  bool showModal = false;

  public void ShowModal()
  {
     showModal = true;
  }
}

When I try to change the <MyModalComponent> state through the @ref, using the modalref.ShowModal() from <FolderComponent>, the state is changed, but the modal does not show. It only shows if I call StateHasChanged() or pass some sort of state [Parameter] from FolderComponent and control the logic that way, why is that?


Solution

  • I can reproduce the issue too, that's because we are using blazor server which is server-side-rendered. Changing bool showModal such value won't trigger the component to be re-rendered.

    By default, Razor components inherit from the ComponentBase base class, which contains logic to trigger rerendering at the following times:

    After applying an updated set of parameters from a parent component. After applying an updated value for a cascading parameter. After notification of an event and invoking one of its own event handlers. After a call to its own StateHasChanged method (see ASP.NET Core Razor component lifecycle).

    When we use @ref to create a reference for the child component and then use the ref to call the methods and change the variable value of inside the child component, the value is changed but the view doesn't re-render. Just like what you shared, we can use StateHasChanged(); to force the child component to re-render.

    @code {
        bool showModal = false;
    
        public void ShowModal()
        {
            showModal = true;
            StateHasChanged();
        }
    }
    

    StateHasChanged notifies the component that its state has changed.

    Notifies the component that its state has changed. When applicable, this will cause the component to be re-rendered.