Skip to content

Static HTML inside @ref element? #28783

Closed
@NightProgramming

Description

@NightProgramming

There is some mentioning of the requirement of @ref elements to be empty:

"Only use an element reference to mutate the contents of an empty element that doesn't interact with Blazor."

"The recommended technique is to have the component's code (.razor file) produce an empty element. As far as Blazor's diffing system is concerned, the element is always empty, so the renderer does not recurse into the element and instead leaves its contents alone."

"The <div> with @ref="mapElement" is left empty as far as Blazor is concerned. The mapbox-gl.js script can safely populate the element and modify its contents."

"It is not safe for external JS code to modify elements that Blazor does not regard as empty."

The warning section says though:

"it's dangerous to mutate the contents of the unordered list (ul) because Blazor interacts with the DOM to populate this element's list items (<li>) from the Todos object"

Also some dangerous sample code is given:

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

The other parts of the page say that @ref elements always should be empty, but the dangerous sample code and the text above it indicate, at least to me, that the danger actually comes from having Blazor manipulating something inside the @ref element (in this case because of the @foreach directive).

Now the obvious question arises: What if there is only static HTML inside the @ref element, e.g.:

<div @ref="MyDiv">
    <p>Some text.</p>
</ul>

And then have some JS that does something with <p> or adds siblings to <p> or whatever.

According to the parts of the page that say that @ref elements always should be empty, it's wrong to do that. But according to what the warning section indicates, it shouldn't be a problem because Blazor shouldn't manipulate anything inside this @ref div element.

Which one holds true? The current docs make it look like there is some uncertainty regarding what can actually cause problems. If @ref elements simply always have to empty then the docs would seem clearer to me without the warning section. Or keep the warning section but then please also explain why having only static HTML inside the @ref also isn't possible. Or if it is possible then please edit the other parts that say that it has to be empty.


Document details

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

Metadata

Metadata

Assignees

Type

No type

Projects

Status

Done

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions