Skip to content

Commit 7b01d3a

Browse files
committed
ssr friendly height computation
1 parent ca1cb33 commit 7b01d3a

2 files changed

Lines changed: 21 additions & 4 deletions

File tree

src/StackedCarousel.jsx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
1-
import React, { useMemo } from "react";
1+
import React from "react";
22
import { useCardStackCarousel } from "./useCardStackCarousel";
33
import CarouselItem from "./CarouselItem";
44
import Navigation from "./Navigation";
5-
import { getRootHeight } from "./getRootHeight";
5+
import { useRootHeight } from "./useRootHeight";
66

77
export function StackedCarousel(props) {
88
const {
@@ -32,6 +32,7 @@ export function StackedCarousel(props) {
3232
transitionDuration,
3333
verticalOffset,
3434
});
35+
const rootHeight = useRootHeight(height);
3536

3637
const renderCards = () => {
3738
return React.Children.map(children, (child, index) => {
@@ -50,7 +51,6 @@ export function StackedCarousel(props) {
5051
};
5152

5253
const { Root } = styleOverrides;
53-
const rootHeight = useMemo(() => Number(getRootHeight(height)), [height]);
5454
const styles = Object.assign({}, Root, { height: rootHeight });
5555

5656
return (
Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
import { useLayoutEffect, useEffect, useState } from "react";
2+
3+
// SSR support
4+
const useIsomorphicLayoutEffect =
5+
typeof window !== "undefined" ? useLayoutEffect : useEffect;
6+
17
const BREAKPOINTS = [
28
{ name: "2xl", value: 1536 },
39
{ name: "xl", value: 1280 },
@@ -6,7 +12,7 @@ const BREAKPOINTS = [
612
{ name: "sm", value: 640 },
713
];
814

9-
export const getRootHeight = (heightProp) => {
15+
const getRootHeight = (heightProp) => {
1016
if (!heightProp) {
1117
throw new Error("'height' prop is required");
1218
}
@@ -37,3 +43,14 @@ export const getRootHeight = (heightProp) => {
3743
throw new Error(`Invalid height prop: ${heightProp}`);
3844
}
3945
};
46+
47+
export const useRootHeight = (heightProp) => {
48+
const [height, setHeight] = useState(0);
49+
50+
useIsomorphicLayoutEffect(() => {
51+
const height = Number(getRootHeight(heightProp));
52+
setHeight(height);
53+
}, [heightProp]);
54+
55+
return height;
56+
};

0 commit comments

Comments
 (0)