Home
Laravel Livewire and jQuery - Not initialized Components Image

Laravel Livewire and jQuery - Not initialized Components

I try to be pretty active on the Laravel Livewire Forums to help people getting started with this awesome tool and today there has been an interesting post by a new user.

The user tried to incorporate Livewire into an existing application which uses jQuery. In his application he has a list of products and for each of these products there is a button to follow it in some way. He tried to create the list using Livewire, but using the existing jQuery functionality to load more products.

The initially loaded products worked fine and they could be followed. But when he loaded more products, the button on the newly loaded ones didn't trigger any action.

The problem has been that the HTML was generated on the server and appended to the list using jQuery. Because of that Livewire had no clue about the newly created components and therefore they haven't been initialized.

My initial thought on this was "why doesn't he simply use Livewire to load more products?". But hey, actually that doesn't really matter, for some reason he couldn't.

At first I wanted to tell him that I think it's not possible what he tries to accomplish. But while writing down my answer it came to my mind, that Livewire somehow needs to check for components itself when it is started, so there could be some function to trigger this. And guess what? There is!

Looking at Livewires "index.js" there is a function called "rescan". And it does exactly what its name suggests. It checks the DOM nodes and inits any component it can find (basically).

So after you have added a new component to the DOM, which has been rendered server-side and got to the frontend on any other way than through Livewire, you can use "window.livewire.rescan()". This will than initialize the new components.

There may be some performance implications using this function, maybe there could be some unwanted side effects, but I think in cases where people are trying to incorporate Livewire into existing Applications by progressive enhancement, it is really helpful to know that it exists! And when the enhancement proceeds, you won't have to use it anymore.

I hope this helps everyone in the same situation!Link to the post in case you are interested:

Livewire Forum