Add custom javascript to a Livewire v3 component

535 Views Asked by At

I am showing a Livewire V3 component within a modal, the modal is created with FilamentPHP V3. I feel like I'm missing something in the documentation (https://livewire.laravel.com/docs/components#executing-scripts) for Livewire because my custom Javascript is not being executed (the @script and @endscript are being printed on the screen).

My FilamentPHP Resource has an action added to the header:

EditInventoryItem.php

class EditInventoryItem extends EditRecord
{
    protected static string $resource = InventoryItemResource::class;

    protected function getHeaderActions(): array
    {
        $actions = [];
        $actions[] = Action::make('print_label')
            ->icon('heroicon-m-star')
            ->action(function (array $data) {
                //
            })
            ->modalContent(view('forms.print-barcode'));

        return $actions;
    }
}

Right now, the only thing the print barcode does is:

print-barcode.blade.php

<livewire:inventory.print-label />

The Livewire component class is:

PrintLabel.php

namespace App\Livewire\Inventory;

use Livewire\Component;

class PrintLabel extends Component
{
    public function render()
    {
        return view('livewire.inventory.print-label');
    }
}

And the print label view:

print-label.blade.php

<div>
    print-label.blade.php
    <div id="adiv"></div>
    @script
      <script>
        console.log('within the root element');
        const adiv = document.getElementById('adiv');
        adiv.innerHTML = 'within the root element';
      </script>
    @endscript
</div>
@script
  <script>
    console.log('outside the root element');
    const adiv = document.getElementById('adiv');
    adiv.innerHTML = 'outside the root element';
  </script>
@endscript

Within the rendered modal, this is what I see: enter image description here

What am I doing wrong?

1

There are 1 best solutions below

0
On

Updating livewire/livewire package should fix this. Version v3.1.0 had this issue at least. Not sure when this got fixed, I will update the answer when I get to know.

Latest one v3.2.1 doesn't have this issue.

To update the package:

composer update livewire/livewire