5 Simple Steps to Create a Blazor Component
Tags: csharp, dotnet, blazor, webdev
Published: 2022-03-10 12:48:18

---
title: 5 Simple Steps to Create a Blazor Component
published: true
date: 2022-03-10 11:38:46 UTC
tags: csharp, dotnet, blazor, webdev
canonical_url: https://www.syncfusion.com/blogs/post/5-simple-steps-to-create-a-blazor-component.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/la1wwo0xgrrvy0uiz329.png
---

The [Blazor](https://en.wikipedia.org/wiki/Blazor "Wikipedia page for Blazor") framework allows developers to build interactive web UI using C# instead of JavaScript. Blazor applications are built using multiple Blazor components. Each Blazor component is a Razor component consisting of an **HTML**  **and**  **CSS** template and [C#](https://en.wikipedia.org/wiki/C_Sharp_(programming_language) "Wikipedia page for C Sharp (programming language)") code. These components are then a portion of the UI that can be shared, reused in an app, and even reused in multiple apps.

In this blog, we are going to see how to create a reusable Blazor component. We will use the standard Blazor Server application template of Visual Studio 2022.

## Prerequisites

To create and run a Blazor server-side web app, we need the following:

- [Visual Studio 2022 / Visual Studio 2019](https://visualstudio.microsoft.com/vs/ "Visual Studio 2022")
- [.NET 6.0 SDK](https://dotnet.microsoft.com/download/dotnet/6.0 "Download .NET 6.0") / [.NET 5.0 SDK](https://dotnet.microsoft.com/download/dotnet/5.0 "Download .NET 5.0") / [.NET Core SDK 3.1.8](https://dotnet.microsoft.com/download/dotnet-core/3.1 "Download .NET Core 3.1")

**Note:**

- .NET Core SDK 3.1.8 requires Visual Studio 2019 16.7 or later.
- .NET 5.0 requires Visual Studio 2019 16.8 or later.
- .NET 6.0 requires Visual Studio 2022 17.0 Preview 4.1 or later.

Let’s see how to create a Blazor component to display the employee details of an organization.

## Step #1: Create a Blazor server-side app.

First, open Visual Studio and [create a Blazor server-side project](https://dotnet.microsoft.com/en-us/learn/aspnet/blazor-tutorial/create "Blazor Tutorial - Build your first Blazor app").

## Step #2: Create the EmployeeCard component.

Let’s create a Blazor component to display details about the employees of an organization.

To add a component to the project, right-click on the **Pages** folder and choose **Add -> Razor Component.**

Refer to the following image.

![Add Razor Component to Blazor Server App](https://www.syncfusion.com/blogs/wp-content/uploads/2022/03/Add-Razor-Component-to-Blazor-Server-App.png)In the Add New Item- Blazor App dialog, provide the name **EmployeeCard**  and click **Add**.

Refer to the following image.

![Naming the Razor component as EmployeeCard](https://www.syncfusion.com/blogs/wp-content/uploads/2022/03/Naming-the-Razor-component-as-EmployeeCard.png)

Now, our employee component is created with the following basic template.

```html
<h3>EmployeeCard</h3>

@code {

}
```

Next, we replace this code with our UI code for the employee details. The markup contains **div, h6, h5,**  **and**  **img** elements. The Blazor Server app project has a **Bootstrap** theme, so we are going to use the **Bootstrap Card** to display the organized content.

Refer to the following code.

```html
<div class="card m-2">
  <div class="card-body">
    <h6 class="card-title text-center">Digital Marketing</h6>
    <h6 class="card-subtitle mb-2 text-muted text-center">Sales Department</h6>
    <div class="card-text text-center">
        <img class="card-img-top" src="../EmployeeImage.png" alt="Card image cap">
        <h5>Margaret</h5>
    </div>
    <div>                
     <h6 class="card-text"><b>ID</b>: <small>124</small></h6>                 
     <h6 class="card-text"><b>Joined</b>: <small>12th July 2012</small> </h6>               
     <h6 class="card-text"><b>Email</b>: <small>margaret@domain.com</small></h6>
   </div>
         
  </div>
</div>
```

### Step #3: Create the parameters to reuse the Blazor component.

Our component is ready. But we have used hard-coded values for the employee details like image, ID, name, and email. A component is a piece of an app that can be used multiple times in the same app.

So, to make our component more dynamic, we replace the hard-coded values with the component parameters provided by the user. Now let’s create the parameters to get these details.

Refer to the following code.

```js
@code {

   [Parameter]
   public string Name {get; set;}

   [Parameter]
   public string Image {get; set;}

   [Parameter]
   public int ID {get; set;}

   [Parameter]
   public string Joined {get; set;}

   [Parameter]
   public string Email {get; set;}

  
}
```

Then, in the Razor page, replace the hard-coded values with the parameters’ values by prefixing **@** to them.

Refer to the following code.

```html
<div class="card m-2">
 <div class="card-body">
    <h6 class="card-title text-center">Digital Marketing</h6>
    <h6 class="card-subtitle mb-2 text-muted text-center">Sales Department</h6>
    <div class="card-text text-center">
        <img class="card-img-top" src="@Image" alt="Card image cap">
        <h5>@Name</h5>
    </div>
    <div>
    <h6 class="card-text"><b>ID</b> : <small>@ID</small></h6>                 
    <h6 class="card-text"><b>Joined</b>: <small>@Joined</small> </h6>
    <h6 class="card-text"><b>Email</b>: <small>@Email</small></h6>
    </div>
         
 </div>
</div>

@code {

   [Parameter]
   public string Name {get; set;}

   [Parameter]
   public string Image {get; set;}

   [Parameter]
   public int ID {get; set;}

   [Parameter]
   public string Joined {get; set;}

   [Parameter]
   public string Email {get; set;}
  
}
```

Now, move the **EmployeeCard.Razor** file to the Shared folder.

### Step #4: Display the employee details.

Now, our Blazor component is ready to be displayed on a page. We can treat the Blazor component itself as a page using the route directives. As of now, we are using the default **Index.razor** page to display the component.

Use the HTML tag with the component name **<EmployeeCard></EmployeeCard>** within the **Index** page and pass the values to the component parameters.

```js
@page "/"

<EmployeeCard Image="../EmployeeImage.png" ID="124" Joined="12th July 2012" Email="margaret@domain.com"></EmployeeCard>
```

Then, run the application and you will see our Blazor component on the index page itself.

![Displaying Single Employee's Details in a Department](https://www.syncfusion.com/blogs/wp-content/uploads/2022/03/Displaying-Single-Employees-Details-in-a-Department.png)

### Step #5: Display multiple employees’ details in a department.

We have displayed the information of just a single employee. But we can use this **EmployeeCard** component to display the details of all the employees in an organization.

Let’s change this page to show the details of the employees working in the Sales Department of the organization.

First, create a Model and Service in the /Data folder of the project to generate some random data for the employees.

In the **EmployeeModel** , declare the fields.

**EmployeeModel**

```csharp
public class EmployeeModel
 {
     public int ID { get; set; }
     public DateTime Joined { get; set; }
     public string Name { get; set; } = "";
     public string Image { get; set; } = "";
     public string Email { get; set; } = "";
 }
```

In the  **EmployeeService** , define the method to generate data.

**EmployeeService**

```csharp
public class EmployeeService
 {
        private static readonly string[] Name = new[]
        {
        "Nancy", "Margaret", "Michael", "Robert", "Anne" 
        };
        private static readonly string[] Mail = new[]
        {
        "nancy@domain.com", "margaret@domain.com", "michael@domain.com", "robert@domain.com","anne@domain.com"
        };

        public Task<EmployeeModel[]> GetEmployeeAsync(DateTime startDate)
        {
            return Task.FromResult(Enumerable.Range(0, 5).Select(index => new EmployeeModel
            {
              Joined = startDate.AddDays(index),
              Name = Name[index],
              Email = Mail[index],
              Image = "../" + Name[index] +".PNG",
              ID = Random.Shared.Next(200, 555)

            }).ToArray());
        }
 }
```

Then, register the **EmployeeService** in the **Program.cs** file to make it available for all the components in the project.

**Program.CS**

```csharp
builder.Services.AddSingleton<EmployeeService>();
```

Inject the **EmployeeService** in the index page using the **@inject** directive. Now, the service is available on the index page. Call the **GetEmployeeAsync** method to generate the array of the Employee model.

Declare the  **employeeDetails**  field to store the data from the service. The data should be loaded when the component is initialized, so use the  **OnInitializedAsync** lifecycle method to get the values.

```js
@using BlazorApp.Data
@inject EmployeeService EmployeeService

@code {
    private EmployeeModel[]? employeeDetails;

    protected override async Task OnInitializedAsync()
    {
        employeeDetails = await EmployeeService.GetEmployeeAsync(DateTime.Now);
    }
}
```

Using the employee details array, create components for each employee and assign the details from the employee service as values of the parameters.

Refer to the following code.

```js
@page "/"

@using BlazorApp.Data
@inject EmployeeService EmployeeService

@if (employeeDetails == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <div class="container">
    <div class="row">       
   @foreach (var employee in employeeDetails)
   {
      <div class="col-lg-4 mb-2">
      <EmployeeCard Name=@employee.Name Image=@employee.Image ID=@employee.ID Joined=@employee.Joined.ToShortDateString() Email=@employee.Email></EmployeeCard>
     </div>
   }  
   </div>
   </div>
}

@code {
    private EmployeeModel[]? employeeDetails;

    protected override async Task OnInitializedAsync()
    {
        employeeDetails = await EmployeeService.GetEmployeeAsync(DateTime.Now);
    }
}
```

Finally, run the application and you can see the details of the employees in the sales department.

![Displaying Multiple Employees' Details in a Department](https://www.syncfusion.com/blogs/wp-content/uploads/2022/03/Displaying-Multiple-Employees-Details-in-a-Department.png)You can use this Blazor component to display all the employee details in the organization in each department.

## GitHub reference

For more details, refer to the complete code example on GitHub for [creating a Blazor component](https://github.com/SyncfusionExamples/Simple-Steps-to-Create-a-Blazor-Component "Simple Steps to Create a Blazor Component demo on GitHub").

## Conclusion

Thanks for reading! I hope you now have a better understanding of how to create a Blazor component. The UI components are the heart of a Blazor application, as they let us reuse the code, reduce our development time, and enhance our productivity. Use this blog post as a reference and try creating your own Blazor component. Leave your feedback in the comments section below!

The Syncfusion [Blazor suite](https://www.syncfusion.com/blazor-components "Syncfusion Blazor UI components ") offers over 70 components that work with both Blazor server-side and client-side (Blazor WebAssembly) projects seamlessly. Use them to build astonishing applications!

For existing customers, the newest version of Essential Studio is available for download from the [License and Downloads](https://www.syncfusion.com/account/downloads "License and download page of Essential Studio") page. If you are not yet a Syncfusion customer, you can try our 30-day [free trial](https://www.syncfusion.com/downloads "Free evaluation of the Syncfusion Essential Studio") to check out the available features.

For questions, you can contact us through our [support forum](https://www.syncfusion.com/forums "Syncfusion support forum"), [support portal](https://support.syncfusion.com/ "Syncfusion support portal"), or [feedback portal](https://www.syncfusion.com/feedback/javascript "Syncfusion Feedback Portal"). We are always happy to assist you!

## Related blogs

- [7 Features of Blazor That Make It an Outstanding Framework for Web Development](https://www.syncfusion.com/blogs/post/7-features-of-blazor-that-make-it-an-outstanding-framework-for-web-development.aspx "7 Features of Blazor That Make It an Outstanding Framework for Web Development blog")
- [Build World-Class Blazor WebAssembly Apps with Globalization and Localization](https://www.syncfusion.com/blogs/post/build-world-class-blazor-webassembly-apps-with-globalization-and-localization.aspx "Build World-Class Blazor WebAssembly Apps with Globalization and Localization blog")
- [Create an Org Chart to Elegantly Visualize Hierarchical Data in Blazor WebAssembly](https://www.syncfusion.com/blogs/post/create-an-org-chart-to-elegantly-visualize-hierarchical-data-in-blazor-webassembly.aspx "Create an Org Chart to Elegantly Visualize Hierarchical Data in Blazor WebAssembly blog")
- [Easily Synchronize Blazor Resource Scheduler with RESTful Services](https://www.syncfusion.com/blogs/post/easily-synchronize-blazor-resource-scheduler-with-restful-services.aspx "Easily Synchronize Blazor Resource Scheduler with RESTful Services blog")