I'm trying to implement a highChart using react and react-grid-layout. The chart should resize according to the react-grid-layout and for that, I need to pass chart.reflow() in the onResizeStop prop of ResponsiveGridLayout. I can get access to the chart in the callback prop of HighchartsReact but I'm not able to figure out how do I get access to the chart in the ResponsiveGridLayout component to pass it in the onResizeStop prop.
import { Responsive, WidthProvider } from 'react-grid-layout';
import Highcharts, { chart } from 'highcharts'
import HighchartsReact from 'highcharts-react-official'
import { useRef, useState } from "react"
import styles from './Blocks.module.css';
const ResponsiveGridLayout = WidthProvider(Responsive);
const options1 = {
title: {
text: 'My chart 1'
},
series: [{
type:'bar',
data: [1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7]
}],
}
const Blocks = (props) => {
const layout1 = [
{ i: "1", x: 0, y: 0, w: 8, h: 8 },
]
const handleResize = chart => {
chart.reflow()
}
return (
<div className={styles.blocks}>
<ResponsiveGridLayout
className="layout"
layouts={layout1}
autoSize={true}
allow-resize={true}
isDraggable
isRearrangeable
isResizable
onResizeStop={handleResize}
breakpoints={{lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0}}
cols={{lg: 12, md: 10, sm: 6, xs: 4, xxs: 2}}
>
<div className={styles.container} key="1" >
<HighchartsReact
containerProps = {{ className: styles.chartContainer }}
highcharts = { Highcharts }
options = { options1 }
callback = { chart => chart}
/>
</div>
</ResponsiveGridLayout>
</div>
)
}
export default Blocks
You can get chart instance by using React useRef
hook:
const chartComponent = useRef(null);
const handleResize = () => {
const chart = chartComponent.current?.chart;
if (chart) {
chart.reflow();
}
};
return (
<HighchartsReact
ref={chartComponent}
...
/>
);
Live demo: https://codesandbox.io/s/highcharts-react-demo-fork-n4y01?file=/demo.jsx
Docs: https://github.com/highcharts/highcharts-react#how-to-get-a-chart-instance