One essential aspect of Blazor are components. They are basically your Blazor code container. This is where you put the UI and the code needed for your UI to behave the way you want it to. You can dissociate the code from the UI but it’s not mandatory. For small component, I would advise to keep your code in the same file as the UI so you don’t have to manage a alot of different files.

  1. What’s a component (concretely)
    A component is just a .razor file that you add to your solution. It consists of HTML code and c# code in the @code (formerly @function) section. Be sure to have the Blazor extension for visual studio installed to make sure visual studio knows it’s a Blazor component

    @page "/counter"
    <p>Current count: @currentCount</p>
    @code {
        int currentCount = 0;
        void IncrementCount()

    @page tells Blazor the name of your component.
    @currentCount : variable declared in the @code section used for databinding
    @onclick : tells Blazor the method (IncrementCount declared in the @code section) to execute when the onclick event is fired.
    @code : section where you put your c# code to be executed in your browser.

  2. How to use the component.
    All you have to do is call it from a parent component


    It’s very easy and straight forward But what if you need some parameters?

  3. Send Parameters to your component
    If you need to adapt a few things in your component, it’s possible to transmit parameters and customize behaviour.
    All you need to do is to create a property in your @code section of your razor component and decorate it with the Parameter attribute.  That way, blazor knows the value of this can be set elsewhere.

    public int currentCount { get; set; }

    You can also specify a default value for your parameter like this :

    public int currentCount { get; set; } = 40;

    and that is how you call you component and set the parameter from the parent :

    <Counter currentCount="25"/>
  4. Separate your c# code from your HTML in your razor component
    If you want to separate the logic code from the HTML because it’s substantial or because you feel more comfortable, you can.  There are few conventions to keep in mind when doing so.

    1. The class where you want to put your code needs to inherit from ComponentBase (Microsoft.AspNetCore.Components.ComponentBase)
      public class CounterBase : ComponentBase
    2. You need to insert in your component (razor file) the reference to your class with an @inherits statement.
      @inherits PagesCode.CounterBase

Taht’s it for today, thanks for reading.