Rendering d3 chart in AG Grid cell — AG Grid with React and Typescript
More posts on AG Grid with React and Typescript:
The problem
We want to have a d3 chart in our grid, so we have <EngagementCellRenderer />
, in which we have a d3 chart. (If you want to know how the d3 chart is implemented, check out this)
But soon we found the chart doesn’t get rendered, my guess is the rendering order. <div id={`engagement-${id}`} />
only gets rendered when the grid is rendered so drawChart()
won’t be able to find the element to mount the chart on.
The Solution
Basically we want to run drawChart()
only after the grid is rendered.
In the <Grid />
component, we run drawChart()
with each row when the grid is rendered, so we have the renderChart()
and we mount it on onFirstDataRendered
.
onFirstDataRendered={renderChart}
And for performance reason, we don’t want to run it on every row but only the rows that’s in the view. In renderChart()
, we check
document.querySelector(`#engagement-${member.company.id}`) && !document.querySelector(`#engagement-${member.company.id} svg`)
So drawChart()
only runs when the element is there and when the chart is not there yet. And then we have to run renderChart()
every time someone scroll on the grid.
onBodyScroll={renderChart}
That’s it =)
More posts on AG Grid with React and Typescript: