C# > Blazor and Web Development > Blazor Components > Creating a Blazor Component
Basic Blazor Component: Counter
This snippet demonstrates how to create a simple Blazor component that increments a counter each time a button is clicked. This is the foundational 'Hello, World!' of Blazor components.
Component Code (@Counter.razor)
This code defines a Blazor component named `Counter`. It includes:
Current count: @currentCountCounter
`: A simple heading.
@page "/counter"
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
Concepts Behind the Snippet
This component demonstrates fundamental Blazor concepts:
Real-Life Use Case
While simple, this demonstrates the core principle for interactive elements. Think of user profile views (incrementing view counts), shopping carts (incrementing item quantities), or simple form validation counters (showing characters remaining).
Best Practices
Interview Tip
Be prepared to explain the Razor syntax, data binding, and event handling used in the component. Understand the Blazor component lifecycle. You might be asked how to pass data to the component or how to handle more complex events.
When to Use Them
Use Blazor components to encapsulate reusable UI elements. This promotes modularity, maintainability, and testability. Any part of your webpage that is interactive, dynamic, and potentially reusable is a good candidate for a Blazor component.
Memory Footprint
This simple component has a very small memory footprint. More complex components with large data sets or frequent updates may require optimization to minimize memory usage and improve performance.
Alternatives
Alternatives to Blazor components include:
Pros
Cons
FAQ
-
What is the purpose of the `@page` directive?
The `@page` directive specifies the route that the component will respond to. When a user navigates to that route in their browser, Blazor will render the component. -
How does data binding work in Blazor?
Data binding in Blazor allows you to connect UI elements to C# variables. When the variable's value changes, the UI automatically updates, and vice versa. The `@` symbol is used to denote C# code within the Razor markup. -
How do I pass data to a Blazor component?
You can pass data to a Blazor component using component parameters. These are properties decorated with the `[Parameter]` attribute.