I am trying to create a highlighted tab system in a Blazor app. Like how you would have an active nav component that is highlighted.
So when a button is clicked on, the background changes the colour to represent it is selected.
I can do this easily using JavaScript by passing e
and having e.id
to get the HTML ID of the element.
However, I am now trying to do this in a Blazor app and I can’t figure out how to complete this code.
First I couldn’t pass a string as a parameter when clicked. So I am now trying to pass the ID of HTML.
How do I pass the parameter?
If that can’t be done, what should I do to make this tabbing system?
Here is some basic code I was playing with to pass the values and change the colour of one of the buttons.
@page "/store"
<PageTitle>Store</PageTitle>
<style>
.tab-button {
background-color: #ccc;
color: #333;
}
/* CSS for selected buttons/tabs */
.tab-button.selected {
background-color: #007bff;
color: #fff;
}
</style>
<div class="h-screen">
<div class="flex h-full">
<section class="hidden md:grid md:grid-rows-nav bg-slate-600 h-full min-w-[250px] border-r-2 border-black border-solid h-full">
<NavMenu />
</section>
<main class="relative w-full h-full grid">
<h3>Store</h3>
<div>
<button id="abc" class="tab-button @(selectedTab == "tab1" ? "selected" : "")" @onclick="() => SelectTab(e)">Tab 1</button>
<button id="xyz" class="tab-button @(selectedTab == "tab1" ? "selected" : "")" @onclick="() => SelectTab(e)">Tab 2</button>
</div>
<div>
@if (selectedTab == "tab1")
{
<p>Content for Tab 1</p>
}
else if (selectedTab == "tab2")
{
<p>Content for Tab 2</p>
}
</div>
</main>
</div>
</div>
@code {
private string selectedTab = "tab1";
private void SelectTab(EventArgs e)
{
Console.WriteLine($"fsdfs {e.id}");
}
}
I tried to pass various params and used eventArgs
With this code, I have ‘e’ as undefined and it is not passing any data. The error mentions it is not defined in context.
3
Answers
The simplest way will be to pass the value as an argument.
Demo @ BlazorFiddle
You can make this dynamic and pass parameters.
Simplest Approach: Use hardcoded element identifier
Better Approach: Use ElementReference