Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 41 ยท Getting Started

Your First Blazor Component

Build your first Blazor component step by step: the @page directive, markup, the @code block, an @onclick handler, reusing a component as a tag, and how the Counter template page works.

The best way to understand Blazor is to write a component. In this lesson you will read the Counter page from the template line by line, then build your own small components and use one inside another. You will meet the four ingredients almost every component has: a route, markup, state and an event handler.

The Counter page

This is Components/Pages/Counter.razor from the template (the render mode line applies to the interactive template):

HTML
@page "/counter"
@rendermode InteractiveServer

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}

Line by line:

  • @page "/counter" makes this component reachable at /counter. Without it, the component can only be used inside others.
  • @rendermode InteractiveServer makes the component interactive (explained in chapter 8). Static pages ignore clicks.
  • <PageTitle> sets the browser tab title through the HeadOutlet.
  • @currentCount writes the field's value into the HTML.
  • @onclick="IncrementCount" calls a C# method when the button is clicked.
  • @code { ... } is a normal C# class body. The compiler turns the whole file into a class named Counter.

When you click, IncrementCount runs, the field changes, Blazor re-renders the component and the paragraph updates. You wrote no JavaScript and no DOM code.

What the compiler really produces

A .razor file is not interpreted at runtime. It is compiled into a C# class that inherits from ComponentBase and overrides BuildRenderTree. Roughly:

C#
public partial class Counter : ComponentBase
{
    private int currentCount = 0;

    protected override void BuildRenderTree(RenderTreeBuilder builder)
    {
        builder.OpenElement(0, "p");
        builder.AddContent(1, "Current count: ");
        builder.AddContent(2, currentCount);
        builder.CloseElement();
        // ...button, handler, and so on
    }

    private void IncrementCount() => currentCount++;
}

The numbers (0, 1, 2) are sequence numbers that help the diff algorithm work quickly. You normally never see this code, but knowing that a component is just a class explains a lot: fields are state, methods are handlers, and every instance of <Counter /> on a page has its own separate count.

A runnable stand-in for a component

Here is a stand-in that behaves like the compiled Counter: a class holding state and building a tree, with an event that triggers a re-render. A tiny Node type plays the role of the render tree.

C# Stand-in: a counter as a class

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The two instances show that state belongs to the component instance: clicking a twice does not affect b.

Building and using your own component

Create Components/Greeting.razor:

HTML
<p class="greeting">Welcome to Blazor, @Name!</p>

@code {
    [Parameter]
    public string Name { get; set; } = "friend";
}

Use it in any page:

HTML
<Greeting Name="Ada" />
<Greeting />

The first line renders "Welcome to Blazor, Ada!", the second uses the default "friend". The attribute Name="Ada" sets the [Parameter] property. Component names start with a capital letter, which is how Blazor tells <Greeting /> apart from an HTML tag like <p>. If the component lives in another folder, add a @using for its namespace (or put it in _Imports.razor).

You can nest components freely. A ProfileCard can contain several <Greeting /> tags, and the page can contain several ProfileCards. Parameters are the subject of Component Parameters.

Code-behind and partial classes

If the @code block grows large, move it to a partial class next to the markup. For Counter.razor, create Counter.razor.cs:

C#
namespace MyFirstApp.Components.Pages;

public partial class Counter
{
    private int currentCount = 0;

    private void IncrementCount() => currentCount++;
}

Then the .razor file contains only markup. Both files compile into one class, so they share members. Visual Studio nests the .cs file under the .razor file automatically. The same trick works for CSS: Counter.razor.css is scoped CSS whose rules apply only to that component.

Start with a single .razor file and split out code-behind only when the code outgrows the markup. Small components are easier to read as one file.

Common mistakes

  • Forgetting the render mode. A click does nothing on a static page. Add @rendermode InteractiveServer (or set it globally) for interactive pages.
  • Lowercase component names. <greeting /> is treated as an unknown HTML element. Use <Greeting />.
  • A missing @using. If <Greeting /> shows the error "element not found", the namespace is not imported.
  • Mutating state without a re-render. Event handlers trigger a re-render automatically. Changes made from other threads or timers need StateHasChanged (see Refs and State Changes).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does @page "/counter" do?

    The @page directive adds a route, making the component a routable page.
  2. 2. What does the compiler turn a .razor file into?

    Each .razor file becomes a C# class with a BuildRenderTree method.
  3. 3. You place <Counter /> twice on one page. What is true about their counts?

    State lives in fields of the component instance, so two instances are independent.
  4. 4. Why must a component name start with a capital letter?

    Capitalized tags are resolved as components; lowercase tags are treated as HTML elements.

Summary

  • A component combines markup and a C# @code block; @page makes it a page.
  • @onclick binds a method to a click, and Blazor re-renders afterwards.
  • A .razor file compiles to a class; every tag usage creates an instance with its own state.
  • Reuse components as capitalized tags and pass data with [Parameter] properties.
  • Large @code blocks can move to a .razor.cs partial class.

Next: How Blazor Renders