Hello, developer! Imagine you’re building your Blazor app and notice something’s missing to enhance user interaction: Toast Notifications. These are those little pop-ups that let you know something happened without interrupting your workflow. Today, weโre going to see how to implement a reusable toast notification component using C# and .NET in Blazor. Let’s get to it!
Why Use Toast Notifications?
Before jumping into the code, you might ask: “Why bother with toast notifications?” Simply put, they provide quick feedback, keep workflow smooth, and add a modern touch to the interface.
Creating Reusable Toast Notifications in Blazor
Toast Service
First up, the Toast Serviceโthe backbone of our notification system. This service will emit events that our toast component will listen for, triggering tasty notifications to appear.
ToastService.cs
// ToastNotificationService domain
namespace ToastNotificationService.ToastMessage
{
public class ToastService
{
// Event for showing toasts
public event Action<string, string, int> OnShow;
// Event for hiding toasts
public event Action OnHide;
/// <summary>
/// Shows a generic toast.
/// </summary>
public void ShowToast(string message, string type = "info", int dismissAfter = 3)
{
OnShow?.Invoke(message, type, dismissAfter);
}
/// <summary>
/// Hides the currently displayed toast.
/// </summary>
public void HideToast()
{
OnHide?.Invoke();
}
// Convenience methods for common toasts
public void ShowSuccess(string message, int dismissAfter = 3) => ShowToast(message, "success", dismissAfter);
public void ShowError(string message, int dismissAfter = 3) => ShowToast(message, "failure", dismissAfter);
public void ShowWarning(string message, int dismissAfter = 3) => ShowToast(message, "warning", dismissAfter);
public void ShowInfo(string message, int dismissAfter = 3) => ShowToast(message, "info", dismissAfter);
public void ShowAlert(string message, int dismissAfter = 3) => ShowToast(message, "alert", dismissAfter);
}
}
This service becomes the maestro conducting the symphony of toasts in your app, allowing messages to show with different flavors: success, error, warning, info, and alert. Register it as a singleton in your appโs Program.cs to ensure thereโs only one toast service available:
builder.Services.AddSingleton<ToastService>();
That’s right, one instance to rule them all!
Toast Component
Toast.razor
@using ToastNotificationService.ToastMessage
@inject ToastService ToastService
@if (ShowMessage)
{
<div class="toast-message-container">
<div class="toast-message-box @MessageTypeClass">
<span class="toast-message-content">@MessageContent</span>
<button class="toast-close-button" @onclick="HideMessage">x</button>
</div>
</div>
}
@code {
// Boolean flag to control toast visibility
private bool ShowMessage { get; set; } = false;
// Message content and type
private string MessageContent { get; set; } = string.Empty;
private string MessageType { get; set; } = "success"; // Default message type
// Determines CSS class based on message type
private string MessageTypeClass => MessageType switch
{
"success" => "toast-message-success",
"failure" => "toast-message-failure",
"alert" => "toast-message-alert",
"warning" => "toast-message-warning",
_ => "toast-message-default"
};
protected override void OnInitialized()
{
ToastService.OnShow += ShowToast; // Subscribe to toast events
ToastService.OnHide += HideMessage;
}
private async void ShowToast(string message, string type, int dismissAfter)
{
MessageContent = message;
MessageType = type;
ShowMessage = true;
await InvokeAsync(StateHasChanged); // Update the UI
if (dismissAfter > 0)
{
await Task.Delay(dismissAfter * 1000);
HideMessage();
}
}
private void HideMessage() => ShowMessage = false; // Hide the toast
public void Dispose()
{
ToastService.OnShow -= ShowToast; // Clean up subscriptions
ToastService.OnHide -= HideMessage;
}
}
Our .razor component listens for events fired by the ToastService and displays the notifications with style. You can think of it as a diligent butler, ensuring your messages are shown and then gently fade away.
Registering and Using the Toast Component
With our ingredients cooked up, let’s set the table by integrating the toast component into your Blazor app’s layout.
MainLayout.razor
@inherits LayoutComponentBase
<Toast /> <!-- Toast Component -->
<div class="page">
<div class="sidebar">
<NavMenu /> <!-- Your navigation menu -->
</div>
<main>
<div class="top-row px-4">
<a href="<https://learn.microsoft.com/aspnet/core/>" target="_blank">About</a>
</div>
<article class="content px-4">
@Body
</article>
</main>
</div>
By nesting the Toast component in the layout, you effortlessly spread the toasty goodness throughout your application. Now, from any component, simply inject the ToastService and fire away!
@using ToastNotificationService.ToastMessage
@inject ToastService ToastService
<button class="btn btn-success" @onclick="() => ToastService.ShowSuccess('You did it!', 3)">Show Success Toast</button>
<button class="btn btn-danger" @onclick="() => ToastService.ShowError('Something went wrong', 3)">Show Error Toast</button>
With a click, your user will see a beautifully styled message appear, as if Gordon Ramsay himself served it up.
Styling Your Toast Notifications
No dish is complete without presentation. Here’s how to style your toast notifications for an eye-catching display:
Toast.razor.css
.toast-message-container {
position: fixed;
top: 20px;
right: 20px;
z-index: 1000;
animation: slide-in 0.5s ease-out, slide-out 0.5s ease-in 5s forwards;
}
.toast-message-box {
display: flex;
align-items: center;
justify-content: space-between;
padding: 15px;
margin-bottom: 10px;
border-radius: 5px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}
.toast-message-success { background-color: #28a745; }
.toast-message-failure { background-color: #dc3545; }
.toast-message-alert { background-color: #ffc107; color: #212529; }
.toast-message-warning { background-color: #ff8800; }
.toast-message-default { background-color: #17a2b8; }
.toast-close-button {
background: none;
border: none;
color: white;
font-size: 16px;
cursor: pointer;
}
.toast-close-button:hover { color: #000; }
/* Slide animations */
@keyframes slide-in {
from { transform: translateX(100%); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
@keyframes slide-out {
from { transform: translateX(0); opacity: 1; }
to { transform: translateX(100%); opacity: 0; }
}
These styles ensure your notifications are served hot and ready, dancing onto the stage and disappearing gracefully.
Wrapping Up
Toast notifications in Blazor offer an elegant way to communicate with users. With a reusable component and a centralized service, youโll manage notifications consistently across your Blazor app. Integrate them and take the user experience to the next level!