Post Impatica
Post Impatica

Reputation: 16373

How to load a JS library in Blazor server razor file?

I'm trying to follow the document HERE to load THIS bootstrap-datepicker within a blazor server app. Note: I want to load it for a single page only without having to load it for all pages.

Within the .razor file I'm trying to do this:

HTML

<input @ref=ReferenceToInputControl class="form-control" id="obdInput">

Code

@code {
    ElementReference ReferenceToInputControl;
    private IJSObjectReference? jsModule;
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
            jsModule = await JS.InvokeAsync<IJSObjectReference>("import", "./js/bootstrap-datepicker.js");
            await jsModule.InvokeVoidAsync("Datepicker", ReferenceToInputControl);
        }
    }

}

I get an error that "Could not find Datepicker. Datepicker was undefined".

I've read so much information about IIFE and scope and closure and modules but I can't for the life of me figure out what I need to do with that function so it will load and I can use it to change the input into a calendar.

Upvotes: 0

Views: 319

Answers (1)

Zac Anger
Zac Anger

Reputation: 7747

That library isn't using ES Modules, so import won't work. The way it's distributed, it's designed to be loaded in a script tag:

<script type="text/javascript" src="js/bootstrap-datepicker.min.js"></script>

You'll also need the CSS from the same repo, as well as jQuery and Bootstrap.

However it's worth noting that that library is fairly old, does not have Bootstrap 5 support, and will need some adjustments to use with Bootstrap 3 or 4 see here.

Upvotes: 1

Related Questions