Search code examples
htmlasp.net-coreblazorblazor-client-sideblazor-component

How to target specific div with Blazor components?


I have a top-row div a follows:

   <div class="top-row px-3">
      <b>App:<i>Title</i></b>

      <!-- wait for it ... -->
      <div class="menu">
         Menu Bar Here
      </div>

   </div>

I am going to have several MenuBar components that will swap out in the div class menu with a button click. How do I target that div with a Blazor component?

Update
I think I found a solution by Chris Sainty.

Edit
To clarify what I intend to accomplish:

I have 2 components:

  • <MenuBar1 />
  • <MenuBar2 />

Both contain different html to construct a simple menu bar. I have navigational links that, when clicked, will raise the onClick event.

How, when the link is clicked, can I swap out the MenuBar components?


Solution

  • Blazor doesn't use Javascript strategy. To do that you have to mix HTML with code.

    <div class="top-row px-3">
        <b>App:<i>Title</i></b>
        <!-- wait for it ... -->
        <div class="menu">
            @if (Version == "v1")
            {
                <p>version 1</p>
            }
            else if (Version == "v2")
            {
                <p>version 2</p>
            }
        </div>
    </div>
    

    For dynamic menu add a file in shared folder. The file name = the class name For example MenuButton.razor

    @inject NavigationManager navManager
    <button @onclick="(e)=>navManager.NavigateTo(route)">@(label)</button>
    
    @code {
        [Parameter]
        public string label { get; set; }
        [Parameter]
        public string route { get; set; }
    }
    

    To consume this componant

    <div class="top-row px-3">
        <b>App:<i>Title</i></b>
        <!-- wait for it ... -->
        <div class="menu">
            <MenuButton label="Choice 1" route="/route1" />
            <MenuButton label="Choice 2" route="/route2" />
        </div>
    </div>