KristofferStrube / Blazor.Popper

A Blazor wrapper for the Javascript library Popper.js
MIT License
27 stars 5 forks source link
align blazor blazor-webassembly blazor-wrapper javascript popper tooltip

License: MIT GitHub issues GitHub forks GitHub stars NuGet Downloads (official NuGet)

Introduction

A Blazor wrapper for the JavaScript library Popper.js

Demo

The sample project can be demoed at https://kristofferstrube.github.io/Blazor.Popper/

Getting Started

Prerequisites

You need to install .NET 6.0 or newer to use the library.

Download .NET 6

Installation

You can install the package via Nuget with the Package Manager in your IDE or alternatively using the command line:

dotnet add package KristofferStrube.Blazor.Popper

Usage

The package can be used in Blazor WebAssembly projects.

Assets

You first need to reference popper.js since this is only a wrapper. You can do this using your favorite JS package manager (e.g. NPM or Library Manager) or just add the following to the body of your index.html file after the point where you reference _framework/blazor.webassembly.js.

<script src="https://unpkg.com/@popperjs/core@2"></script>

Import

You also need to reference the package in order to use it in your pages. This can be done in _Import.razor by adding the following.

@using KristofferStrube.Blazor.Popper

Add to service collection

An easy way to make Popper available in all your pages is by registering it in the IServiceCollection so that it can be dependency injected in the pages that need it. This is done in Program.cs by adding the following before you build the service collection.

public static async Task Main(string[] args)
{
    var builder = WebAssemblyHostBuilder.CreateDefault(args);
    builder.RootComponents.Add<App>("#app");

    // Other services are added.

    builder.Services.AddScoped<Popper>();

    await builder.Build().RunAsync();
}

Inject in page

In any page that need a popper you can then inject Popper by adding the following to the top of the razor file.

@inject Popper Popper;

Then you can use Popper to create a popper instance between two ElementReference's like so:

<span @ref=reference>reference</span>
<span @ref=popper>popper</span>

@code {
    protected ElementReference reference;
    protected ElementReference popper;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await Popper.CreatePopperAsync(reference, popper, new());
    }
}

Related articles

This repository was build on top of the work done in the following series of articles: