Integrating External JavaScript Libraries with Livewire 3.0

Integrating JavaScript Libraries with Livewire 3.0

Step 1: Choosing a JavaScript Library

For this example, we’ll integrate Chart.js, a popular JavaScript library for creating interactive charts, into a Livewire component. However, the principles covered can be applied to any library such as Alpine.js, jQuery, or FullCalendar.

Step 2: Setting Up Chart.js

1. Install Chart.js

Use npm or yarn to install Chart.js in your Laravel project:


npm install chart.js

After installation, compile your assets:


npm run dev

2. Include Chart.js in Your Layout

In your main Blade layout file (e.g., resources/views/layouts/app.blade.php), include the compiled JavaScript file:


<script type="rocketlazyloadscript" src="{{ mix('js/app.js') }}" defer></script>

Step 3: Creating the Livewire Component

Run the following command to create a Livewire component:


php artisan make:livewire ChartComponent

This generates:

  1. app/Livewire/ChartComponent.php – The PHP logic for the component.

  2. resources/views/livewire/chart-component.blade.php – The Blade view for the component.

ChartComponent.php

Update the PHP logic to include some sample data for the chart:


<?php

namespace App\Livewire;

use Livewire\Component;

class ChartComponent extends Component
{
    public $chartData;

    public function mount()
    {
        $this->chartData = [
            'labels' => ['January', 'February', 'March', 'April', 'May'],
            'datasets' => [
                [
                    'label' => 'Sales',
                    'backgroundColor' => 'rgba(75, 192, 192, 0.2)',
                    'borderColor' => 'rgba(75, 192, 192, 1)',
                    'data' => [65, 59, 80, 81, 56],
                ],
            ],
        ];
    }

    public function updateChart()
    {
        $this->chartData['datasets'][0]['data'] = [75, 69, 90, 91, 66];

        $this->dispatch('updateChart', $this->chartData);
    }

    public function render()
    {
        return view('livewire.chart-component');
    }
}

Step 4: Building the Blade View

In the chart-component.blade.php file, create a canvas element for the chart and initialize it using Livewire hooks:


<div>
    <canvas id="salesChart"></canvas>

    <script type="rocketlazyloadscript">
        document.addEventListener('livewire:load', () => {
            const ctx = document.getElementById('salesChart').getContext('2d');

            const chart = new Chart(ctx, {
                type: 'bar',
                data: @js($chartData),
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                },
            });

            Livewire.on('updateChart', (newData) => {
                chart.data = newData;
                chart.update();
            });
        });
    </script> <button wire:click="updateChart">Update Chart</button></div>

What’s Happening Here?

  1. livewire:load: Ensures the JavaScript runs after the Livewire component is loaded.

  2. @js: Converts the PHP array $chartData into a JSON object for use in JavaScript.

  3. Livewire.on: Listens for events from the Livewire component to dynamically update the chart.

Step 5: Triggering Dynamic Updates

The updateChart method in the component modifies the chart data and dispatches an event to update the chart in real time. The JavaScript listener in the Blade view handles the dynamic update by calling the chart.update() method

Step 6: General Tips for JavaScript Integration

  1. Use dispatch: Communicate between Livewire and JavaScript by emitting events with dispatch.

  2. Leverage livewire:load: Ensure JavaScript initializes after Livewire components are rendered.

  3. Keep Logic Separate: Use JavaScript files or inline scripts for external library logic to maintain clean code.

Final Output

With the above setup, your Livewire component will:

  1. Display a dynamic bar chart using Chart.js.

  2. Update the chart data in real time with a button click.

  3. Provide seamless integration between Livewire and JavaScript.

Key Features Covered Today

  1. Installing and configuring external JavaScript libraries in Laravel Livewire.

  2. Using livewire:load to initialize JavaScript after component rendering.

  3. Dynamically updating external library elements with Livewire events.

  4. Best practices for JavaScript and Livewire integration.

© Copyright 2025 Wontonee. All Right Reserved.

×How can I help you?