0

I'm using Chart.js inside a Lightning Community app and I'm having trouble creating a simple chart. Here's my script declaration (note that the moment.min.js is required for the Chart.js to work) :

<ltng:require scripts="{!join(',',
    $Resource.BundleResources + '/BundleResources/js/moment.min.js',
    $Resource.BundleResources + '/BundleResources/js/Chart.min.js')}" 
      afterScriptsLoaded="{!c.init}"/>  

and here's my rendere javascript file :

afterRender : function(component, helper)
{
    this.superAfterRender();

    try
    {
        var canvas = document.getElementById('networkChart');
        var ctx = canvas.getContext('2d');

        // below is the standard Chart.js example found in their documentation
        var youpi = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['label1', '2', 'et 3'],
                data: [1, 2, 3, 4, 5, 6],
                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: {
                    yAxes: [{
                        ticks: {
                            beginAtZero:true
                        }
                    }]
                }
            }
        });
    }catch(e){
        helper.logError('catched error : ' + e);
    }
}

and below is the error the console is giving me :

catched error : ReferenceError: Chart is not defined

My Chart.min.js is well included, no error on this side. Does anybody knows where I failed ? Thank you !

2

afterRender will be called before ltng:require loads the required scripts. You need to wait until the afterScriptsLoaded method is called (in other words, your init method).

  • well... This was a quick fix, thanks :-) – metheM Jan 9 at 14:29

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.