Search code examples
navigationblazormaui

.NET MAUI Blazor On page navigation


There seems to be very little on the subject.

How can you click a button or an < a > tag and navigate to a different part of the page?

The only way I thought was possible was using simple html anchor tags that point to an element Id, sadly this does not work.

I would like vanilla MAUI Blazor options but if a third party component works, that's fine too.


Solution

  • I have created a new sample to test and used the js function to scroll to the element id replace the scrolling.

    In the index.html:

    <script>
         window.scrollToElementId = (elementId) => {
              console.info('scrolling to element', elementId);
              var element = document.getElementById(elementId);
              if (!element) {
                     console.warn('element was not found', elementId);
                 }
              element.scrollIntoView();
           }
    </script>
    

    In the razor:

    @inject IJSRuntime js
    
    <button class="btn btn-primary" @onclick="ScrollTo">Goto The Element</button>
    
      .... a lot of elements
    
    <p id="ap">The bottom of the page.</p>
    
    @code {
          private void ScrollTo()
          {
                ScrollToElementId("ap");
          }
          private async void ScrollToElementId(string elementId)
          {
                await js.InvokeVoidAsync("scrollToElementId", elementId);
          }
    }