How to create NavMenu with collapsible submenu in .Net Core Blazor app

Sorush picture Sorush · Nov 18, 2019 · Viewed 9k times · Source

I am trying to create a blazor navmenu which has a shape like this

  • item a

  • item b

when I click on item b it expands with sub menu like this and clicking on subitems, new pages open

  • item a

  • item b

    • subitem 1

    • subitem 2

I just edited the original blazor app but no success. The button appears but it doesn't collapse submenu. any idea?

<div class="@NavMenuCssClass" @onclick="@ToggleNavMenu">
<ul class="nav flex-column">
    <li class="nav-item px-3">
        <NavLink class="nav-link" href="" Match="NavLinkMatch.All">
            <span class="oi oi-home" aria-hidden="true"></span> Home
        </NavLink>
    </li>
    <li class="nav-item px-3">
        <NavLink class="nav-link" href="counter">
            <span class="oi oi-plus" aria-hidden="true"></span> Counter
        </NavLink>
    </li>
    <li class="nav-item px-3">
        <NavLink class="nav-link" href="fetchdata">
            <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch Data
        </NavLink>
    </li>
    <li class="dropdown">

        <button data-toggle="collapse" data-target="#demo">Collapsible</button>

        <div id="demo" class="collapse">
            <ul>
                <li class="nav-item px-3">
                    <NavLink class="nav-link" href="meeting">
                        <span class="oi oi-plus" aria-hidden="true"></span> Meetings
                    </NavLink>
                </li>
                <li class="nav-item px-3">
                    <NavLink class="nav-link" href="conference">
                        <span class="oi oi-list-rich" aria-hidden="true"></span> Conferences
                    </NavLink>
                </li>
                <li class="nav-item px-3">
                    <NavLink class="nav-link" href="event">
                        <span class="oi oi-list-rich" aria-hidden="true"></span> Events
                    </NavLink>
                </li>

            </ul>
        </div>

    </li>
</ul>

Answer

Postlagerkarte picture Postlagerkarte · Nov 18, 2019

Do not use the data-toggle and data-target for it.

These are used by boostrap.js however you do not want to modify the DOM in that way.

What you do instead is to use an if statement and thus let Blazor take care of the rendering:

    <NavLink class="nav-link" @onclick="()=>expandSubNav = !expandSubNav">
        <span class="oi oi-list-rich" aria-hidden="true"></span> Fetch data
    </NavLink>
    @if (expandSubNav)
    {
        <NavLink class="expand-menu" href="">
            <span>Sub1</span>
        </NavLink>
        <NavLink class="" href="">
            <span>Sub2</span>
        </NavLink>
    }

And put the expandSubNav field into your code section:

@code {

    private bool expandSubNav;

}