Use flickity in Blazor server

Viewed 105

I'm trying to use the flickity js library (https://flickity.metafizzy.co/) in my Blazor server application. For some reason, I can't get it to work, even though I tried a lot of different scenarios.

This is how it looks right now:

  1. I added the CSS and javascript files in _Host.chtml
<link href="https://npmcdn.com/flickity@2/dist/flickity.css" rel="stylesheet" />

 <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
            integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
            crossorigin="anonymous"></script>
 
<script src="https://npmcdn.com/flickity@2/dist/flickity.pkgd.js" crossorigin="anonymous"></script>
  1. I added the code for the carousel in the page:
 <div class="main-carousel">
        <div class="carousel-cell">1</div>
        <div class="carousel-cell">2</div>
        <div class="carousel-cell">3</div>

    </div>
  1. In _Host.chtml I then created this function:
 window.initF = () => {
            $('.main-carousel').flickity({
                // options
                cellAlign: 'left',
                contain: true
            });
        }
  1. In the page I then try to initiate it:
@inject IJSRuntime js

@functions{
    protected async override Task OnAfterRenderAsync(bool firstrender)
    {
        if (firstrender)
        {
            await js.InvokeAsync<object>("initF");

            firstrender = false;
        }
    }
}

But for some reason, it doesn't work.

Someone that has an idea what I'm missing?

1 Answers

This seems to work fine for me.

I have tried it in blazor fiddle and took the CSS from the library's website, and works similar to the demo they have there. See attachment

Can you remove one line from your code where you assign firstrender value, as this is automatically handled:

protected async override Task OnAfterRenderAsync(bool firstrender)
{
    if (firstrender)
    {
        await js.InvokeAsync<object>("initF");

        // firstrender = false; <- remove this assignment
    }
}
Related