5 Simple Steps to Create a Blazor Component | Syncfusion Blogs
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (175).NET Core  (29).NET MAUI  (208)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (41)Black Friday Deal  (1)Blazor  (220)BoldSign  (14)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (66)Flutter  (133)JavaScript  (221)Microsoft  (119)PDF  (81)Python  (1)React  (101)Streamlit  (1)Succinctly series  (131)Syncfusion  (919)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (159)Xamarin  (161)XlsIO  (36)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (150)Chart  (132)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (633)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (40)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (508)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (11)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (387)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (597)What's new  (333)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
5 Simple Steps to Create a Blazor Component

5 Simple Steps to Create a Blazor Component

The 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# 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:

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.

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 AppIn the Add New Item- Blazor App dialog, provide the name EmployeeCard and click Add.

Syncfusion’s Blazor components suite is the expert’s choice for building modern web apps.

Refer to the following image.

Naming the Razor component as EmployeeCard

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

<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.

<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.

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

<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.

@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

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.

Everything a developer needs to know to use Blazor components in the Blazor app is completely documented.

EmployeeModel

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

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

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.

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

Explore the different application UIs developed using Syncfusion Blazor components.

Refer to the following code.

@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 DepartmentYou 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.

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 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 page. If you are not yet a Syncfusion customer, you can try our 30-day free trial to check out the available features.

For questions, you can contact us through our support forumsupport portal, or feedback portal. We are always happy to assist you!

Related blogs

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed