Php Published July 01, 2021

How to use select2 with livewire

post

Most of the developers are facing select2 styles removing issue when livewire render the component.

We can resolve this issue by using a livewire javascript hook.

Here is my screen with select2 before livewire component rendering.

And when the livewire component is refreshed means re-render the select2 style is gone ☹️

How to Fix it ?? 🤔

Well you just need to add some JQuery code to your livewire component. here we are going to use afterDomUpdate webhook of livewire. add following code to your livewire component :

document.addEventListener('livewire:load', function (event) {

    window.livewire.hook('afterDomUpdate', () => {

        $('#select2ID').select2();

    });

});

livewire:load is listening events when livewire component is load and we can add our code within it.

And now when your livewire component is refreshed your select2 style will be still there as we are again applying it.

Other Livewire Posts :

Setup livewire with component example

How to use livewire pagination

Stay tuned to us for more interesting stuffs about livewire.