How to use select2 with livewire

Laravel
September 03, 20201 minuteuserVishal Ribdiya
How to use select2 with livewire

Most of the developers are facing a select2 style removing issue when livewire renders the component.

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

Here is my screen with select2 before livewire component rendering.

2020-12-10_5fd2207b2f583

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

2020-12-10_5fd221ec084b8

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 the following code to your livewire component :

document.addEventListener('livewire:load', function (event) {
   window.livewire.hook('afterDomUpdate', () => {         
   $('#select2ID').select2();     
   }); 
});

livewire:load is listening events when the livewire component is loaded 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:

Stay tuned to us for more interesting stuff about livewire.