C
C#14mo ago
Felizola

❔ Editing the DOM with JS and Blazor

Hey, I'm building a UI with Blazor Server and I have a question about JS interacting with the DOM in Blazor. I need to build the html content of a component through Javascript, while still using Blazor... In my program, the first render, that is prerendered on the server, works wonderfully. But Blazor does a diff of the DOM, finds out that it doesn't match, and removes the content that was added by the Javascript code. I saw the warnings in the documentation about doing this (https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/?view=aspnetcore-7.0#interaction-with-the-dom), and I need to know the right way of doing it. I managed to prevent this by using JSInterop with OnAfterRenderAsync, but this adds a 3 seconds delay to building the Javascript component, which is unacceptable. Here is a minimal repro of this behavior with two components: TestComponent and TestPage
//TestPage.razor
@page "/"
<TestComponent/>
//TestPage.razor
@page "/"
<TestComponent/>
//TestComponent.razor
@using System.Globalization
<div id="test"></div>
@((MarkupString)$@"
<script>
let element = document.getElementById(""test"");
element.innerHTML = ""The date in the server is {DateTime.Now.ToString(CultureInfo.InvariantCulture)}""
</script>
")
//TestComponent.razor
@using System.Globalization
<div id="test"></div>
@((MarkupString)$@"
<script>
let element = document.getElementById(""test"");
element.innerHTML = ""The date in the server is {DateTime.Now.ToString(CultureInfo.InvariantCulture)}""
</script>
")
Do you have any ideas on how to do this?
ASP.NET Core Blazor JavaScript interoperability (JS interop)
Learn how to interact with JavaScript in Blazor apps.
1 Reply
Accord
Accord14mo ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server