Blazor Components Fundamentals
Welcome to the fundamental concepts of Blazor components. Components are the building blocks of a Blazor application, enabling you to create reusable UI elements.
What are Blazor Components?
Blazor components are .NET classes that encapsulate rendering logic. They are defined using Razor syntax, a powerful combination of C# and HTML. Components are highly reusable and can be nested within each other to build complex user interfaces.
Creating Your First Component
Let's create a simple component named WelcomeMessage.razor
:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Welcome</title>
</head>
<body>
<h1>Hello, @Name!</h1>
@code {
[Parameter]
public string Name { get; set; } = "World";
}
</body>
</html>
Component Parameters
Components can accept input parameters to customize their behavior and appearance. These parameters are defined as public properties marked with the [Parameter]
attribute.
In the example above, the Name
property allows us to pass a name to the WelcomeMessage
component. We can use it like this:
<WelcomeMessage Name="Blazor Developer" />
This will render:
Hello, Blazor Developer!
Component Lifecycle
Blazor components have a lifecycle that includes several methods that are invoked at different stages of their existence. Key lifecycle methods include:
OnInitialized()
: Called when the component is initialized.OnInitializedAsync()
: Asynchronous version ofOnInitialized()
.OnParametersSet()
: Called when component parameters are set or changed.OnParametersSetAsync()
: Asynchronous version ofOnParametersSet()
.OnAfterRender(bool firstRender)
: Called after the component has been rendered. Useful for interacting with the DOM.OnAfterRenderAsync(bool firstRender)
: Asynchronous version ofOnAfterRender()
.
OnInitializedAsync()
.
Nesting Components
Components can contain other components, creating a hierarchical structure. This is fundamental to building complex UIs.
For example, a Layout.razor
component might contain a header, footer, and a placeholder for the main content, which is then populated by other components.
Component Rendering
When a component's state changes, Blazor re-renders the component and updates the DOM efficiently. This is handled automatically by Blazor's rendering engine.
Component Interaction
Components can communicate with each other through various mechanisms, including:
- Event Callbacks: Allow child components to notify parent components of events.
- Cascading Values and Parameters: Enable data to be passed down the component tree without explicit passing through every level.
Next Steps
Now that you understand the fundamentals of Blazor components, you can explore more advanced topics such as data binding, event handling, and routing.