Blazor Component Libraries: Building Reusable UI

On this page

Razor Class Libraries (RCLs) allow you to share Blazor components across multiple apps. With .NET Core 3.1 and upcoming .NET 5, they now support including static assets (CSS, JS, images) inside the NuGet package. This guide builds a reusable “Modal” component library.

Project Structure

Create a new RCL project:

Bash1 line
dotnet new razorclasslib -o MyCompany.Components --support-pages-and-views

Static Web Assets

Place CSS in the `wwwroot` folder of the library. It is automatically exposed to the consuming app at `_content/{LibraryName}/{Path}`.

HTML2 lines
<!-- Consuming App (index.html) -->
<link href="_content/MyCompany.Components/styles.css" rel="stylesheet" />

Building the Modal Component

C#24 lines
<!-- Modal.razor -->
@if (IsVisible)
{
    <div class="modal-backdrop">
        <div class="modal-content">
            @ChildContent
            <button @onclick="Close">Close</button>
        </div>
    </div>
}

@code {
    [Parameter] public RenderFragment ChildContent { get; set; }
    [Parameter] public EventCallback OnClose { get; set; }
    
    public bool IsVisible { get; private set; }
    
    public void Open() => IsVisible = true;
    public void Close()
    {
        IsVisible = false;
        OnClose.InvokeAsync(null);
    }
}

Key Takeaways

  • RCLs are the standard for sharing UI.
  • Static assets are bundled automatically; no webpack required.
  • Use `EventCallback` for child-to-parent communication.

Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Written by

Nithin Mohan TK

Hello Namaste! 👋🏻 I'm an accomplished Enterprise Solution Architect & Engineering Leader with 20+ years of progressive experience architecting, building, and scaling transformative enterprise solutions. ⚜️ Solution Architect / AI & Cloud 📌 Galway, Ireland

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.