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:

  • `@page "/counter"`: This directive specifies the route for this component. Visiting `/counter` in the browser will render this component.
  • `

    Counter

    `: A simple heading.
  • `

    Current count: @currentCount

    `: Displays the current value of the `currentCount` variable.
  • ``: A button that, when clicked, calls the `IncrementCount` method. `@onclick` is an event handler.
  • `@code { ... }`: This section contains the C# code for the component.
  • `private int currentCount = 0;`: Declares an integer variable named `currentCount`, initialized to 0. This holds the counter's value.
  • `private void IncrementCount() { currentCount++; }`: A method that increments the `currentCount` variable by 1.

@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:

  • Razor Syntax: Blazor uses Razor syntax, a combination of HTML and C# code.
  • Directives: Directives like `@page` provide instructions to the Blazor compiler.
  • Data Binding: The `@currentCount` syntax is an example of data binding. When `currentCount` changes, the UI automatically updates.
  • Event Handling: The `@onclick` attribute binds the button's click event to the `IncrementCount` method.
  • Component Lifecycle: Although not explicitly shown here, components have a lifecycle (initialization, rendering, etc.).

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

  • Keep components small and focused.
  • Use clear and descriptive variable names.
  • Separate UI logic from business logic when the complexity of the app increases.
  • Consider using component parameters to make components reusable.

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:

  • Plain HTML/JavaScript: Suitable for very simple UI elements.
  • JavaScript Frameworks (React, Angular, Vue): Offer more features and flexibility but require JavaScript development.
  • Server-Side Rendering: For scenarios where SEO is critical and initial load time is paramount.

Pros

  • Reusability: Components can be reused throughout the application.
  • Maintainability: Changes to a component only need to be made in one place.
  • Testability: Components can be easily tested in isolation.
  • .NET ecosystem: Leverage existing .NET skills and libraries.

Cons

  • Learning Curve: Requires learning Blazor-specific syntax and concepts.
  • Client-Side Blazor (WebAssembly) Download Size: The initial download size can be larger than a simple HTML/JavaScript application.
  • Debugging: Debugging WebAssembly applications can be more challenging than server-side applications.

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.