Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamically resize charts #69

Merged
merged 2 commits into from
Feb 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions frontend/src/components/EChart.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { useTheme } from "@mui/material/styles";
import * as echarts from "echarts";
import { CSSProperties, useEffect, useRef } from "react";
import { useComponentWidthOf } from "./hooks";

interface EChartProps {
width?: CSSProperties["width"];
Expand All @@ -14,6 +15,9 @@ export function EChart({ width, height, option }: EChartProps) {
const theme = useTheme();
const themeMode = theme.palette.mode;

/// Get the width of the parent div to resize dynamically
const parentDivWidth = useComponentWidthOf(ref);

useEffect(() => {
if (chartRef.current) {
echarts.dispose(chartRef.current);
Expand All @@ -39,8 +43,16 @@ export function EChart({ width, height, option }: EChartProps) {
}

chart.setOption(option);
chart.resize();
chartRef.current = chart;
}, [option, themeMode]);

// Resize dynamically
useEffect(() => {
if (chartRef.current) {
chartRef.current.resize();
}
}, [parentDivWidth]);

return <div ref={ref} style={{ width, height }}></div>;
}
25 changes: 25 additions & 0 deletions frontend/src/components/hooks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { RefObject, useEffect, useState } from "react";

/// A hook to get the component width of a Ref to a `HTMLElement`.
export function useComponentWidthOf(ref: RefObject<HTMLElement>) {
// The state.
const [parentWidth, setParentWidth] = useState(0);
useEffect(() => {
// If the ref is null, we do nothing
if (ref.current) {
// Create the observer
const resizeObserver = new ResizeObserver((entries) => {
for (const entry of entries) {
setParentWidth(entry.contentRect.width);
}
});

// Initialize
resizeObserver.observe(ref.current);

// Disconnect the observer on disconnect
return () => resizeObserver.disconnect();
}
}, [ref]);
return parentWidth;
}
Loading