Search code examples
c#cssmaterializeblazorweb-frontend

Materialize CSS examples are not working in Blazor WASM


I'm trying to use the materialize framework for css with a Blazor application, however, when I copy/paste some of the examples into a layout, component, etc I don't get what Materialize shows on the example. There aren't any CSS/JS loading or console errors that can be identified in dev tools, but it seems like something isn't loading because lots of components aren't working as the examples show.

For example, the tab indicator that apperas under the active tab and hops from tab to tab when you select one.

layout page:

@inherits LayoutComponentBase

<div class="main">
    <nav class="nav-extended">
        <div class="nav-wrapper">
        <a href="#" class="brand-logo">Logo</a>
        <a href="#" data-target="mobile-demo" class="sidenav-trigger"><i class="material-icons">menu</i></a>
        <ul id="nav-mobile" class="right hide-on-med-and-down">
            <li><a href="sass.html">Sass</a></li>
            <li><a href="badges.html">Components</a></li>
            <li><a href="collapsible.html">JavaScript</a></li>
        </ul>
        </div>
        <div class="nav-content">
        <ul class="tabs tabs-transparent">
            <li class="tab"><a href="#test1">Test 1</a></li>
            <li class="tab"><a class="" href="#test2">Test 2</a></li>
            <li class="tab disabled"><a href="#test3">Disabled Tab</a></li>
            <li class="tab"><a href="#test4">Test 4</a></li>
        </ul>
        </div>
    </nav>

    <div class="content px-4">
        @Body
    </div>
</div>


Edit

Looks like the M.AutoInit() isn't firing properly. Can someone point out where the best place to call that function would be? I tried a

document.onload = M.AutoInit();

on the index.html page and a interop JS on my component

@code {
    ...
    protected override void OnInitialized()
    {
        JSRuntime.Invoke<string>("M.AutoInit");
    }
    ...
}

Neither worked but maybe I'm doing the JSInterop wrong, couldn't find a definitive example, similar to what I'm trying to do, in the docs. Any suggestions or pointers would be great!


Solution

  • This works for me(very important respect the async await, so if you have any errors the Exception is properlly thowed to your browser console)

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        
        await base.OnAfterRenderAsync(firstRender);
        if (firstRender)
        {
    
            await JSRuntime.InvokeVoidAsync("M.AutoInit");
    
        }
    }