With the introduction of react and echart to make a page, the page has multiple charts, each chart is a component, how to make the echarts chart adaptive?

clipboard.png

Mar.18,2021

listens to the resize event of window and calls the resize method of the echarts instance


if you are using an unencapsulated echarts, you can only adjust the width and height manually. Echarts does not support self-adaptation by default, at least I think the authorities have not found relevant information;
has not looked for other versions of the icon library, so I do not know if there is any adaptive;


window.onresize = myChart.resize;


multiple charts just avoid overriding the window.onresize method.

of course, if multiple components are batch processed, you might as well write a high-level component to encapsulate it.

const ChartWrapper = ChildComponent => class extends Component {
    componentDidMount() {
        if (window) {
            const onresize = window.onresize;
            window.onresize = () => {
                if (onresize) onresize();
                this.child.resize();
            };
        }
    }

    render() {
        return (
            <ChildComponent {...this.props} ref={(child) => { this.child = child; }} />
        );
    }
};

export default ChartWrapper;

then make sure that the resize method is implemented internally for each subcomponent.

class Line extends Component {
    resize = () => {
        // myChart.resize();
    };
}

export default ChartWrapper(Line);
// 
class Bar extends Component {
    resize = () => {
        // myChart.resize();
    };
}

export default ChartWrapper(Bar);

window.addEventListener('resize',function(){
            mychart.resize();
        })

just listen for resize events.

Menu