Using Charts in your Express app with ChartJS
You can find the sample working code here
For simplicity we'll just use CDN links to set up chartjs in your project. You can also read the docs here
Add this your respective .hbs
file or the layout.hbs
file in the <head>
tag.
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.1.1/chart.min.js" integrity_no="sha512-BqNYFBAzGfZDnIWSAEGZSD/QFKeVxms2dIBPfw11gZubWwKUjEgmFUtUls8vZ6xTRZN/jaXGHD/ZaxD9+fDo0A==" crossorigin="anonymous"></script>
<canvas id="myChart" width="400" height="400"></canvas>
We've used myChart
as the id
attribute of the element, but the name is not important, you can choose any sensible id
value
While passing variables to your hbs
file ensure you JSON.stringify
the variables you want the chart to use
//ROUTE TO SHOW BAR CHART
app.get("/", (req, res, next) => {
// Assume we get some data from our DB
let chartData = [12, 19, 3, 5, 2, 3]
let chartLabels = ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange']
// Sending some data to the hbs page
// since our data will be used in JS script in the hbs we will stringify it
// this will ensure that we can use the data with the same encoding in the hbs page
res.render("barChart.hbs", {
chartData: JSON.stringify(chartData),
chartLabels: JSON.stringify(chartLabels)
});
});
In your hbs
file you can access the chartData
and chartLabels
variable in the script tag this way
<script>
console.log( {{{chartData}}} ) // prints [12, 19, 3, 5, 2, 3]
console.log( {{{chartLabels}}} ) //prints ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange']
</script>
to access any variable passed from handlebars we need to use the quotes and three curly opening/closing brackets
"{{{ VARIABLE }}}"
<script>
const ctx = document.getElementById('myChart').getContext('2d');
// The value of 'charLabels' we get from our routes is ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"]
// the value of 'chartData' we get is [12,19,3,5,2,3]
const myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: {{{chartLabels}}},
datasets: [{
label: '# of Votes',
data: {{{chartData}}},
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
borderWidth: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
</script>
The above code can also be found in the docs here
Your page should now look like this (except the nav elements)
Check the docs and the example code on how you can implement all of the different variations of charts
Happy coding! ❤️