Creating a component

In the Client app create a new folder named Components. This is not a special name, we can choose any name we wish.

Once you’ve created the new Components folder, create a file within it named MyFirstComponent.razor and enter the following mark-up.

<div>
    CurrentCounterValue in MyFirstComponent is @CurrentCounterValue
</div>

@code {
    int CurrentCounterValue { get; set; }
}

Now edit the Counter.razor file. At this point we can either reference the component with a fully qualified name:

<CreatingAComponent.Client.Components.MyFirstComponent/>

Or edit /_Imports.razor and add @using CreatingAComponent.Client.Components. The using statements here are cascaded into all Razor views – which means the mark-up to use the new component in /Pages/Counter.razor no longer needs a namespace.

@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

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

<MyFirstComponent/>

@code {
    int currentCount = 0;

    void IncrementCount()
    {
        currentCount++;
    }
}

Now run the app and go to the Counter page.