dotnet / AspNetCore.Docs

Documentation for ASP.NET Core
https://docs.microsoft.com/aspnet/core
Creative Commons Attribution 4.0 International
12.54k stars 25.31k forks source link

ElementRef used for the DOM in javascript or not? #12020

Closed thatnerdyguy closed 5 years ago

thatnerdyguy commented 5 years ago

Right below the warning of "Do not use captured element references as a way of populating the DOM. Doing so may interfere with the declarative rendering model." You then immediately turn around and say giving that reference to javascript to use with DOM APIs (which I would assume includes adding new elements under it) is just fine.

Can you provide some clarification here?

Specifically, what is the pattern when you want Blazor to render most of the page, but then "hand off" some DOM node to some JS library to provide more functionality (like an animated chart, or fancy 3d canvas, or feature-full datagrid, etc...)


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

guardrex commented 5 years ago

Hello @thatnerdyguy. Might need to loosen that language a bit in the warning. The warning came from engineering, so I'll mark this issue with the DR label and add it to the Blazor project for triage. I can't guarantee an ETA on a response, but you will get an answer. Stand-by until engineering gets a little time to look at this. 🏃😅

danroth27 commented 5 years ago

@SteveSandersonMS Do you want to comment here?

SteveSandersonMS commented 5 years ago

I'd say it's OK to use an ElementRef to mutate the contents of an element that, as far as Blazor is concerned, is empty. For example to have some 3rd-party JS lib inject content there. Example:

<div ref="Something"></div>

That's OK because Blazor is not going to be trying to control the contents of that element. Blazor has nothing to put inside it.

However, it's not smart to mutate the contents of an element that Blazor does control, e.g.:

<ul ref="MyList">
    @foreach (var item in Todos)
    {
        <li>@item.Text</li>
    }
</ul>

If you use JS interop to mutate the contents of element MyList, then Blazor will later try to apply diffs to it, and the diffs won't match up with the DOM, and terrible things will happen.