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.
Use npm or yarn to install Chart.js in your Laravel project:
npm install chart.js
After installation, compile your assets:
npm run dev
In your main Blade layout file (e.g., resources/views/layouts/app.blade.php
), include the compiled JavaScript file:
Run the following command to create a Livewire component:
php artisan make:livewire ChartComponent
This generates:
app/Livewire/ChartComponent.php
– The PHP logic for the component.
resources/views/livewire/chart-component.blade.php
– The Blade view for the component.
Update the PHP logic to include some sample data for the chart:
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');
}
}
In the chart-component.blade.php
file, create a canvas element for the chart and initialize it using Livewire hooks:
livewire:load
: Ensures the JavaScript runs after the Livewire component is loaded.
@js
: Converts the PHP array $chartData
into a JSON object for use in JavaScript.
Livewire.on
: Listens for events from the Livewire component to dynamically update the chart.
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
Use dispatch
: Communicate between Livewire and JavaScript by emitting events with dispatch
.
Leverage livewire:load
: Ensure JavaScript initializes after Livewire components are rendered.
Keep Logic Separate: Use JavaScript files or inline scripts for external library logic to maintain clean code.
With the above setup, your Livewire component will:
Display a dynamic bar chart using Chart.js.
Update the chart data in real time with a button click.
Provide seamless integration between Livewire and JavaScript.
Installing and configuring external JavaScript libraries in Laravel Livewire.
Using livewire:load
to initialize JavaScript after component rendering.
Dynamically updating external library elements with Livewire events.
Best practices for JavaScript and Livewire integration.
410 C, Jaina Tower-1, District Center, Janak Puri New Delhi-110058, India.
© Copyright 2025 Wontonee. All Right Reserved.