Skip to content

Instantly share code, notes, and snippets.

@SteveSandersonMS
Created November 15, 2018 11:33
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save SteveSandersonMS/f10a552e1761ff759b1631d81a4428c3 to your computer and use it in GitHub Desktop.
Blazor tab example
@page "/"
<TabSet>
<Tab Title="First tab">
<h4>First tab</h4>
This is the first tab.
</Tab>
@if (showSecondTab)
{
<Tab Title="Second">
<h4>Second tab</h4>
You can toggle me.
</Tab>
}
<Tab Title="Third">
<h4>Third tab</h4>
<label>
<input type="checkbox" bind=@showSecondTab />
Toggle second tab
</label>
</Tab>
</TabSet>
@functions
{
bool showSecondTab;
}
using Microsoft.AspNetCore.Blazor;
public interface ITab
{
RenderFragment ChildContent { get; }
}
@implements IDisposable
@implements ITab
<li>
<a onclick=@Activate class="nav-link @TitleCssClass" href="">
@Title
</a>
</li>
@functions {
[CascadingParameter] TabSet ContainerTabSet { get; set; }
[Parameter] string Title { get; set; }
[Parameter] public RenderFragment ChildContent { get; private set; }
string TitleCssClass => ContainerTabSet.ActiveTab == this ? "active" : null;
protected override void OnInit()
{
ContainerTabSet.AddTab(this);
}
public void Dispose()
{
ContainerTabSet.RemoveTab(this);
}
void Activate()
{
ContainerTabSet.SetActivateTab(this);
}
}
.nav-tabs .nav-link {
border-color: #dee2e6 #dee2e6 #fff;
border-bottom-color: #dee2e6;
background-color: #f9f9f9;
}
.nav-tabs .active {
border-top: 4px solid #e0108b !important;
padding-top: 5px;
border-bottom: 1px solid transparent;
background-color: white;
}
.nav-tabs > li {
margin-bottom: -1px;
}
.nav-tabs-body {
border: 1px solid #dee2e6;
border-top-width: 0;
}
<!-- Display the tab headers -->
<CascadingValue Value=this>
<ul class="nav nav-tabs">
@ChildContent
</ul>
</CascadingValue>
<!-- Display body for only the active tab -->
<div class="nav-tabs-body p-4">
@ActiveTab?.ChildContent
</div>
@functions {
[Parameter] RenderFragment ChildContent { get; set; }
public ITab ActiveTab { get; private set; }
public void AddTab(ITab tab)
{
if (ActiveTab == null)
{
SetActivateTab(tab);
}
}
public void RemoveTab(ITab tab)
{
if (ActiveTab == tab)
{
SetActivateTab(null);
}
}
public void SetActivateTab(ITab tab)
{
if (ActiveTab != tab)
{
ActiveTab = tab;
StateHasChanged();
}
}
}
@develax
Copy link

develax commented Mar 26, 2019

  1. When I use Index.cshtml as a page relative to the root URL ("/tabs" for example) clicking on any tab component leads to the root page "/". Here is the fix:
// Setting `javascript:void(0)` to `href` helps but the project has to be rebuilt then (just F5 runs as if there were no changes).

<a onclick=@Activate class="nav-link @TitleCssClass" href="javascript:void(0)">
    @Title
</a>
  1. StateHasChanged(); sometimes causes an error when the debugger is stopped:
Exception thrown: 'System.InvalidOperationException' in Microsoft.AspNetCore.Components.dll
An exception of type 'System.InvalidOperationException' occurred in Microsoft.AspNetCore.Components.dll but was not handled in user code
The current thread is not associated with the renderer's synchronization context. Use Invoke() or InvokeAsync() to switch execution to the renderer's synchronization context when triggering rendering or modifying any state accessed during rendering.

@hardcoreslacker
Copy link

hardcoreslacker commented Jun 8, 2020

Using Blazor w/.NET Core 3.1 I had to change pages to Blazor components (very minimal changes); but I was having the same problem as DevelAx, where clicking on other tabs brought me to the root. I changed the same line in Tab.razor to:

<li>
    <a @onclick="Activate" class="nav-link @TitleCssClass" href="" @onclick:preventDefault>
        @Title
    </a>
</li>

@pylvr
Copy link

pylvr commented Oct 20, 2020

Can someone explain/comment this code , i dont undersand why he used the "RenderFragment ChildContent" in both tabSet an tab

@knuxbbs
Copy link

knuxbbs commented Oct 23, 2020

This example is not feasible for use with components, within any tab, that have routes.

@hardcoreslacker
Copy link

The top level where you use the TabSet will be the only routable component, the ChildContent of the tab set are the individual tabs, and the ChildContent of the tabs are your controls. Here's a simple example of how I'm using the code.

@page "/control"
@using Microsoft.AspNetCore.Components.Authorization
@using LocalDataAccessLibrary
@using UI.Shared.Tabs 

@inject AuthenticationStateProvider AuthenticationStateProvider
@inject UserData _userData


<AuthorizeView>
    <Authorized>
        <h3>Control</h3>
            <TabSet>
                @if (_roles != null && _roles.Contains("Admin"))
                {
                    <Tab Title="Users">
                        <UsersControl />
                    </Tab>
                    <Tab Title="Global">
                        <GlobalControl />
                    </Tab>
                }
                @if (_roles != null && _roles.Contains("Manager"))
                {
                    <Tab Title="Teams">
                        <TeamsControl UserName="@_userName" />
                    </Tab>
                }
                <Tab Title="Profile">
                    <ProfileControl />
                </Tab>
            </TabSet>
    </Authorized>
    <NotAuthorized>
        <p>Please <a href="Identity/Account/Login">Log in</a> to continue</p>
    </NotAuthorized>
</AuthorizeView>

@code {

  private List<string> _roles;
  private string _userName;

  protected override async Task OnInitializedAsync() {
    var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
    var user = authState.User;
    _userName = user.Identity.Name;

    if (user.Identity.IsAuthenticated) {
      _roles = await _userData.GetUsersRolesAsync(_userName);
    }
    else {
      _roles = new List<string>();
    }
  }
}

@Netsurfer2
Copy link

I was thinking... can you use AJAX or J-Query in a Blazor Page?... AJAX has a tabbed control.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment