Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to force Blazor to re-render a component

Tags:

I'm building a simple web app with Blazor (client-side) and need to get Blazor to re-render the component. Is there way to notify the framework to re-render?

On this Razor page, I have a simple checkbox that shows if the web app is granted a certain permission by user.

ShouldRender() always returns True. When isGranted field is set to True, the checkbox isn't rendered and remains unchecked.

Razor page:

@page "/foo" @inject IJSRuntime js  <input type="checkbox" disabled @bind="isGranted" /> Some Permission  @code {   bool isGranted;    protected override async Task OnInitAsync() {     await js.InvokeAsync<object>(       "foo.bar",       DotNetObjectRef.Create(this),       nameof(BarCallback)     );   }    [JSInvokable]   public void BarCallback(bool result) {     Console.WriteLine($"BarCallback(result: {result})");     isGranted = result;   }   protected override bool ShouldRender() {     Console.WriteLine("Blazor is checking for re-rendering...");     return true;   } } 

JavaScript function:

window.foo = {   bar: (dotnetObjRef, callback) => {     navigator.storage.persist()       .then(result => {         dotnetObjRef.invokeMethodAsync(callback, result)           .catch(reason => console.warn('Failed to call .NET method.', reason));       })       .catch(reason => console.warn('Failed to get permission.', reason));   } } 

Output in the Chrome's console:

WASM: Blazor is checking for re-rendering... WASM: BarCallback(result: True) 

.NET Core SDK: 3.0.100-preview6-012264

Blazor Template: Microsoft.AspNetCore.Blazor.Templates::3.0.0-preview6.19307.2

like image 551
Poulad Avatar asked Jul 01 '19 16:07

Poulad


People also ask

How do I refresh the Blazor component without reloading the page?

You can refresh the Blazor component using the SignalR concept without reloading the page. When using SignalR, saving the changes in one page notifies the changes made to other clients.

How do you render a component on button click in Blazor?

In the method you check if it´s a single left click, single right click, double left etc. and fill your string variable accordingly (e. g. stringClicked = "leftsingle" ). Then you can show components by evaluating the value of a string variable.

What is RenderFragment in Blazor?

A templated component is defined by specifying one or more component parameters of type RenderFragment or RenderFragment<TValue>. A render fragment represents a segment of UI to render. RenderFragment<TValue> takes a type parameter that can be specified when the render fragment is invoked.


1 Answers

Usually, you force a re-render by calling the StateHasChanged method.

For this app to work, you should place StateHasChanged(); at the end of the BarCallback method.

Hope this helps.

like image 138
enet Avatar answered Oct 13 '22 04:10

enet