Skip to content

Add OnMounted component lifecycle event #49497

Closed
@marinasundstrom

Description

@marinasundstrom

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe the problem.

I want to invoke JavaScript after a pre-rendered server component has been mounted in the browser. But I can't find a way to do it.

It used to be (with Razor Pages) that you did it in OnAfterRender which ran twice, and you checked firstRender. For Blazor Server, that meant that if it was true then you where running in the browser and was able to invoke JavaScript. While for WebAssembly you had to check for it to be false.

In Blazor Server in .NET 8, it doesn't work that way.

And this behavior is reasonable. It makes sense that when you have pre-rendered a server component you have already rendered it, and there is no need to call the lifecycle event method again.

To me it makes the most sense to add a new event method indicating that the code has been materialized or "mounted" in the browser.

Describe the solution you'd like

Add an OnMounted() lifecycle method that is executed after OnAfterRender has been executed the first time and the component has been added to the Browsers DOM and the SignalR connection is up and running

This will enable the to execute logic when the component has been mounted - like invoking JavaScript,

@inject IJSRuntime JS

<div id="obj">Hello</div>

@code 
{
    protected async Task OnMountedAsync()
    {
        // The component has been mounted in the DOM and is ready for interactivity.

        await JS.InvokeVoidAsync("hello");
    }
}

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs: Author FeedbackThe author of this issue needs to respond in order for us to continue investigating this issue.area-blazorIncludes: Blazor, Razor Components

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions