2

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?

1

1 Answer 1

9
  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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.