Skip to content

Commit 7814c39

Browse files
ChristopherChudzickijonkafton
authored andcommitted
fix carousel initial positioning (#1546)
1 parent 48388d9 commit 7814c39

File tree

1 file changed

+32
-9
lines changed

1 file changed

+32
-9
lines changed

frontends/ol-components/src/components/Carousel/Carousel.tsx

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -31,14 +31,31 @@ type CarouselProps = {
3131
nextLabel?: string
3232
}
3333

34-
const SlickStyled = styled(Slick)({
35-
/**
36-
* This is a fallback. The carousel's width should be constrained by it's
37-
* parent. But if it's not, this will at least prevent it from resizing itself
38-
* beyond the viewport width.
39-
*/
40-
maxWidth: "100vw",
41-
})
34+
const SlickStyled = styled(Slick)<{ rendered: boolean }>(({ rendered }) => [
35+
{
36+
/**
37+
* This is a fallback. The carousel's width should be constrained by it's
38+
* parent. But if it's not, this will at least prevent it from resizing itself
39+
* beyond the viewport width.
40+
*/
41+
maxWidth: "100vw",
42+
".slick-track::before": {
43+
// By default slick has empty string content on the ::before pseudo
44+
// element, which interferes with spacing on initial render.
45+
content: "none",
46+
},
47+
},
48+
!rendered && {
49+
".slick-track": {
50+
/**
51+
* When react-slick renders on the server, it sets `style="width: 0px;"`
52+
* on the `.slick-track` element. This, combined with auto margoins,
53+
* causes the carousel to render with strange positioning initially.
54+
*/
55+
width: "unset !important",
56+
},
57+
},
58+
])
4259

4360
/**
4461
* Return the current slide and the sliders per paged, based on current element
@@ -125,7 +142,7 @@ const Carousel: React.FC<CarouselProps> = ({
125142
nextLabel = "Show next slides",
126143
}) => {
127144
const [slick, setSlick] = React.useState<Slick | null>(null)
128-
const [slidesPerPage, setSlidesPerPage] = React.useState<number>(1)
145+
const [slidesPerPage, setSlidesPerPage] = React.useState<number>(4)
129146
/**
130147
* The index of the first visible slide.
131148
* slick-carousel marks this slide with slick-current.
@@ -155,6 +172,11 @@ const Carousel: React.FC<CarouselProps> = ({
155172
slick.slickPrev()
156173
}, [slick])
157174

175+
const [rendered, setRendered] = React.useState(false)
176+
React.useEffect(() => {
177+
setRendered(true)
178+
}, [])
179+
158180
const arrows = (
159181
<>
160182
<ActionButton
@@ -184,6 +206,7 @@ const Carousel: React.FC<CarouselProps> = ({
184206
<>
185207
<SlickStyled
186208
className={className}
209+
rendered={rendered}
187210
ref={setSlick}
188211
variableWidth
189212
initialSlide={initialSlide}

0 commit comments

Comments
 (0)