Skip to content

Commit 20d3e9a

Browse files
fix: handle ParallaxLayers inside fragments (#1667) (#1671)
* fix: add check for React.Fragment children * refactor: make child mapping a resursive function * docs: add note about direct children of Parallax Co-authored-by: Josh <[email protected]>
1 parent 720f83a commit 20d3e9a

File tree

2 files changed

+21
-2
lines changed

2 files changed

+21
-2
lines changed

docs/src/pages/components/parallax.mdx

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ import { Parallax, ParallaxLayer } from '@react-spring/parallax'
5959

6060
### Usage Notes
6161

62+
- All direct `children` of `Parallax` must be `ParallaxLayer`s (or `fragment`s whose only direct `children` are `ParallaxLayer`s).
6263
- `Parallax` is a scrollable container so all scroll events are fired from the container itself -- listening for scroll on `window` won't work.
6364
- `scrollTo` is a method on `Parallax` -- you access it with a `ref` and then `ref.current.scrollTo(pageNumber)`.
6465

packages/parallax/src/index.tsx

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,24 @@ function getScrollType(horizontal: boolean) {
1414
return horizontal ? 'scrollLeft' : 'scrollTop'
1515
}
1616

17+
function mapChildrenRecursive(
18+
children: React.ReactNode,
19+
callback: Function
20+
): React.ReactNode {
21+
const isReactFragment = (node: any) => {
22+
if (node.type) {
23+
return node.type === React.Fragment
24+
}
25+
return node === React.Fragment
26+
}
27+
28+
return React.Children.map(children, (child: any) =>
29+
isReactFragment(child)
30+
? mapChildrenRecursive(child.props.children, callback)
31+
: callback(child)
32+
)
33+
}
34+
1735
const START_TRANSLATE_3D = 'translate3d(0px,0px,0px)'
1836
const START_TRANSLATE = 'translate(0px,0px)'
1937

@@ -339,14 +357,14 @@ export const Parallax = React.memo(
339357
...props.innerStyle,
340358
}}>
341359
<ParentContext.Provider value={state}>
342-
{React.Children.map(
360+
{mapChildrenRecursive(
343361
children,
344362
(child: any) => !child.props.sticky && child
345363
)}
346364
</ParentContext.Provider>
347365
</a.div>
348366
<ParentContext.Provider value={state}>
349-
{React.Children.map(
367+
{mapChildrenRecursive(
350368
children,
351369
(child: any) => child.props.sticky && child
352370
)}

0 commit comments

Comments
 (0)