0

I have a custom component and when it's rendered in the browser, I need to measure its size (in JavaScript) and call back to Blazor.

How do I register JavaScript to invoke after rendering of particular component is done?

Liero
  • 19,054
  • 16
  • 100
  • 195

1 Answers1

3
  1. Include a script in your wwwroot.
  2. Reference it in index.html or _Host.cshtml file
  3. In your component add @inject IJSRuntime JSRuntime
  4. Add a @ref to the element you wish to measure <div @ref=MeasureMe>
  5. In your @code declare a field ElementReference MeasureMe
  6. Override OnAfterRenderAsync and do var whatever = JSRuntime.InvokeAsync<YourResultType>("yourJSFunctionName", MeasureMe)

Note: If you have server side prerendering enabled, do not use JSRuntime for the first time until after OnAfterRenderAsync has been executed with firstRender == true.

Also note: Components do not re-render when the browser is resized.

I have a section on JSInterop on Blazor University.

Peter Morris
  • 13,426
  • 8
  • 61
  • 112