Skip to content

Commit

Permalink
Merge pull request #16 from wri/fix-chart-dimensions
Browse files Browse the repository at this point in the history
Resize chart with ResizeObserver
  • Loading branch information
kamicut authored Dec 20, 2024
2 parents 1d5d688 + 41ac5ae commit 8c3a417
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
34 changes: 27 additions & 7 deletions src/components/BarChart.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useRef } from "react";
import { useEffect, useRef, useState } from "react";
import * as d3 from "d3";
import T from "prop-types";

Expand All @@ -7,15 +7,35 @@ const BarChart = ({ data }) => {
const chartRef = useRef();
const tooltipRef = useRef();

const [ chartDimensions, setChartDimentsions ] = useState([0, 0]);

useEffect(() => {
if (containerRef.current) {
const observer = new ResizeObserver(entries => {
const e = entries[0];
const parentElement = e.target.parentElement;
setChartDimentsions([parentElement.clientWidth, parentElement.clientHeight]);
});
observer.observe(containerRef.current);

return () => {
observer.disconnect();
};
}
}, []);

useEffect(() => {
// Exit effect if at least one dimesion is 0
if (!chartDimensions.every(x => !!x)) return;

const svg = d3.select(chartRef.current);
svg.selectAll("*").remove();

const tooltip = d3.select(tooltipRef.current);

const width = containerRef.current?.offsetWidth || 250;
const height = 230;
const margin = { top: 20, right: 20, bottom: 20, left: 60 };
const margin = { top: 24, right: 12, bottom: 36, left: 60 };
const width = chartDimensions[0];
const height = chartDimensions[1];

const x = d3.scaleBand()
.domain(data.map(d => d.category))
Expand Down Expand Up @@ -64,14 +84,14 @@ const BarChart = ({ data }) => {
.on("mouseout", () => {
tooltip.style("visibility", "hidden");
});
}, [data]);
}, [data, chartDimensions]);

return (
<div style={{ position: "relative" }} ref={containerRef}>
<svg
ref={chartRef}
width={containerRef.current?.offsetWidth || 250}
height={230}
width={chartDimensions[0]}
height={chartDimensions[1]}
/>
<div
ref={tooltipRef}
Expand Down
1 change: 0 additions & 1 deletion src/components/ChatOutput.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ function ChatOutput() {
observer.disconnect();
};
}

}, []);

return (
Expand Down

0 comments on commit 8c3a417

Please sign in to comment.