Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ChartJs 3.x: ResizeObserver is not a constructor

I'm trying to use ChartJs in LWC, I took the last 3.3.2 version and followed several examples in order to create my chart (here one of the most complete example I found), but when invoking the instruction:

this.chart = new window.Chart(ctx, config);

I get the error "TypeError: ResizeObserver is not a constructor".

I tried to replace the ChartJs resource with older versions, and I found with the version 2.8.0 the chart is correctly loaded without any error.

Since from documentation is specified the 3.x version introduces several improvements, so I would prefer to use a recent version instead of the 2.8.0. I've tried also to search some info about the ResizeObserver but I didn't understand what is and why I have problems with it. From LWC it seems I haven't to import anything else.

Is there a way to resolve this problem?

like image 939
zeldez Avatar asked Apr 27 '26 00:04

zeldez


2 Answers

It could be you are attempting to run it in a browser/version combination which does not support ResizeObserver.

You can check this and see if your browser version supports it: https://www.caniuse.com/resizeobserver

If not, you can use a polyfill to add the needed behaviour, such as this one: https://github.com/juggle/resize-observer

like image 179
Stephan Pieterse Avatar answered Apr 28 '26 12:04

Stephan Pieterse


I encountered the same issue with Chart.Js - but fortunately you can turn off responsiveness and implement your own version.

I just posted the below here: https://salesforce.stackexchange.com/questions/379134/how-to-use-loadscript-with-light-dom-in-lwc-getting-error-invariant-violation/383560#383560

createChart() {
    const element = this.querySelector('[data-id="chart"]');
    const config = deepClone(this._chartConfiguration);
    //Ensure that the responsiveness is disabled as ResizeObserver
    //is not supported by the LockerService
    if (!config.options) {
        config.options = {
            responsive: false
        };
    } else {
        config.options.responsive = false;
    }
    this.chartInstance = new Chart(
        element.getContext("2d"),
        config
    );
    this.chartInstance.resize();
}

connectedCallback() {
    try {
        window.addEventListener(
            "resize",
            this.handleWindowResize
        );
    } catch (ex) {
        //Handle this
    }
}

disconnectedCallback() {
    try {
        window.removeEventListener(
            "resize",
            this.handleWindowResize
        );
    } catch (ex) {
        //Handle this
    }
}

handleWindowResize = () => {
    if (this.chartCreated === true) {
        this.chartInstance.resize();
    }
}

Link to Chart.Js docs on responsiveness: https://www.chartjs.org/docs/latest/configuration/responsive.html

like image 41
Nic Edwards Avatar answered Apr 28 '26 14:04

Nic Edwards