Skip to content

Instantly share code, notes, and snippets.

@mpskovvang
Created November 25, 2021 22:22
Show Gist options
  • Save mpskovvang/44eabfd64994fede455c96a7fce033c1 to your computer and use it in GitHub Desktop.
Save mpskovvang/44eabfd64994fede455c96a7fce033c1 to your computer and use it in GitHub Desktop.
Laravel Livewire with Chart.js
import { Chart, LineController, LineElement, PointElement, LinearScale } from 'chart.js';
Chart.register(LineController, LineElement, PointElement, LinearScale);
window.lineChart = () => {
return {
chart: null,
init() {
this.drawChart(this.$wire);
},
drawChart(component) {
this.chart = new Chart(this.$refs.ctx, {
type: 'line',
data: component.get('data'),
options: {
scales: {
x: {
type: 'linear',
},
y: {
type: 'linear',
}
}
}
})
}
}
}
<div
x-data="{ ...lineChart() }"
x-init="init()"
>
<canvas wire:ignore x-ref="ctx"></canvas>
</div>
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class LineChart extends Component
{
public $data;
public function mount()
{
$this->data = [
'labels' => [1, 2, 3, 4, 5, 6, 7],
'datasets' => [
[
'label' => 'My First Dataset',
'data' => [65, 59, 80, 81, 56, 55, 40],
'tension' => 0.1,
]
]
];
}
public function render()
{
return view('livewire.line-chart');
}
}
@mpskovvang
Copy link
Author

A basic example to illustrate how to implement Chart.js in a Livewire project.

Typically, you would pass a data object or model to the component like <livewire:line-chart :data="$data" />. Alternately, you could extend the base class and load the data directly from the database or an external service.

Styling could be achieved with:

  1. Global configuration (Chart.defaults.line.borderWidth = 2;).
  2. Custom styling in lineChart component function.
  3. Reading a style property from the component with component.get('...').

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment