In Blazor, developing a web application requires creating numerous components, each with distinct behaviour and appearance, designed for reuse across various sections of your site. This approach can help you reduce code duplication while ensuring consistency within your website, improving the credibility of your web app. This tutorial will discuss the following topics:
A component is intended to be created once and used multiple times to eliminate the need for repeating code. A component does not always need to look the same.
For example, consider you have a textbox with a label to collect input from the user. The textbox will be used in many places to collect user data. To make a component that can be used in multiple scenarios, a meaningful label should be used in each place, making every textbox in your app "slightly different". You can declare these "slight differences" as component parameters to allow them to be changed when needed. Not only do these parameters allow changing the shape of a component, but they also provide a way to enable component communication.
Consider a textbox to capture user input and validate user input as they type (logic). When the user inputs invalid data, the textbox appears with a red border (styling) and turns green when the data is valid. Both logic and styling of a component can be declared and reused in a component. The logic is preserved in the .razor
file, where CSS styling is scoped in the .razor.css
file.
Breaking a big component into multiple smaller components is similar to breaking a large C# method into several smaller ones. It depends on the experience of the developer and the viewpoint of each person. We suggest breaking into multiple components when a piece of UI with the same logic is used in multiple places, or the logic in the UI is too complex, and one way to simplify it is to break it into multiple components.
Create a new Razor Component by right-clicking a folder within your project in Visual Studio and selecting Add > Razor Component... and name it—e.g., BlazorSchoolInputText.razor
The file name will serve as the component's tag.Here's an textbox component example with 2 parameters:
<label> @Label: <input type="text" @bind-value="Value" @bind-value:event="oninput" class="@InputClass" /> </label> @code { [Parameter] public string Label { get; set; } = "Input"; [Parameter] public string Value { get; set; } = ""; private string InputClass => IsValid() ? "valid" : "invalid"; private bool IsValid() => Value.Length > 3; // Basic validation rule }
To maintain a consistent and reusable appearance for your component you can optionally add a scoped CSS file named BlazorSchoolInputText.razor.css
.
.valid { border: 2px solid green; } .invalid { border: 2px solid red; }
So far, you have learnt the basics of creating a reusable component. To fully understand and design good components, we will talk about the following topics to help you leverage your Blazor development skills: