From 44089a382342d8cb47b0106cab245f422cc868c6 Mon Sep 17 00:00:00 2001 From: alexandre Date: Mon, 16 Oct 2023 17:05:26 +0200 Subject: [PATCH] fix SSR --- .../x-charts/src/ChartsXAxis/ChartsXAxis.tsx | 9 +++++++-- packages/x-charts/src/hooks/useMounted.ts | 20 +++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 packages/x-charts/src/hooks/useMounted.ts diff --git a/packages/x-charts/src/ChartsXAxis/ChartsXAxis.tsx b/packages/x-charts/src/ChartsXAxis/ChartsXAxis.tsx index 2e140628dd67..a227179a0da2 100644 --- a/packages/x-charts/src/ChartsXAxis/ChartsXAxis.tsx +++ b/packages/x-charts/src/ChartsXAxis/ChartsXAxis.tsx @@ -11,6 +11,7 @@ import { getAxisUtilityClass } from '../ChartsAxis/axisClasses'; import { AxisRoot } from '../internals/components/AxisSharedComponents'; import { ChartsText, ChartsTextProps, getWordsByLines } from '../internals/components/ChartsText'; import { getMinXTranslation } from '../internals/geometry'; +import { useMounted } from '../hooks/useMounted'; const useUtilityClasses = (ownerState: ChartsXAxisProps & { theme: Theme }) => { const { classes, position } = ownerState; @@ -33,10 +34,11 @@ function addLabelDimension( { tickLabelStyle: style, tickLabelInterval, - }: Pick, + isMounted, + }: Pick & { isMounted: boolean }, ): (TickItemType & LabelExtraData)[] { const withDimension = xTicks.map((tick) => { - if (tick.formattedValue === undefined) { + if (!isMounted || tick.formattedValue === undefined) { return { ...tick, width: 0, height: 0 }; } const tickSizes = getWordsByLines({ style, needsComputation: true, text: tick.formattedValue }); @@ -91,6 +93,8 @@ function ChartsXAxis(inProps: ChartsXAxisProps) { }, } = React.useContext(CartesianContext); + const isMounted = useMounted(); + const defaultizedProps = { ...defaultProps, ...settings, ...props }; const { position, @@ -144,6 +148,7 @@ function ChartsXAxis(inProps: ChartsXAxisProps) { const xTicksWithDimension = addLabelDimension(xTicks, { tickLabelStyle: axisTickLabelProps.style, tickLabelInterval, + isMounted, }); const labelRefPoint = { diff --git a/packages/x-charts/src/hooks/useMounted.ts b/packages/x-charts/src/hooks/useMounted.ts new file mode 100644 index 000000000000..298fc91f814c --- /dev/null +++ b/packages/x-charts/src/hooks/useMounted.ts @@ -0,0 +1,20 @@ +import * as React from 'react'; +import useEnhancedEffect from '@mui/utils/useEnhancedEffect'; + +export function useMounted(defer = false) { + const [mountedState, setMountedState] = React.useState(false); + + useEnhancedEffect(() => { + if (!defer) { + setMountedState(true); + } + }, [defer]); + + React.useEffect(() => { + if (defer) { + setMountedState(true); + } + }, [defer]); + + return mountedState; +}