Laravel

How to use select2 with livewire

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.

livewire

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

livewire componen

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.

Share On: