Skip to content

Commit db32ac8

Browse files
MastroLindusoliviertassinari
authored andcommitted
Fix get display same slide (#480)
* change getDisplaySameSlide.js to handle children arrays Current code of getDisplaySameSlide.js was not handling correctly the situation of having children inside an array (common case for dynamic amount of children). Updated the code so that we use React.Children that traverses nested children arrays * Update getDisplaySameSlide.js * remove parentheses to make linter happy * Update getDisplaySameSlide.js * Make linter happy by adding some parentheses * Update getDisplaySameSlide.js * fix getDisplaySameSlide * add test
1 parent 85f1754 commit db32ac8

File tree

2 files changed

+30
-5
lines changed

2 files changed

+30
-5
lines changed

packages/react-swipeable-views-core/src/getDisplaySameSlide.js

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
1+
import React from 'react';
2+
13
const getDisplaySameSlide = (props, nextProps) => {
24
let displaySameSlide = false;
5+
const getChildrenKey = child => (child ? child.key : 'empty');
36

47
if (props.children.length && nextProps.children.length) {
5-
const oldChildren = props.children[props.index];
6-
const oldKey = oldChildren ? oldChildren.key : 'empty';
8+
const oldKeys = React.Children.map(props.children, getChildrenKey);
9+
const oldKey = oldKeys[props.index];
710

8-
if (oldKey !== null) {
9-
const newChildren = nextProps.children[nextProps.index];
10-
const newKey = newChildren ? newChildren.key : 'empty';
11+
if (oldKey !== null && oldKey !== undefined) {
12+
const newKeys = React.Children.map(nextProps.children, getChildrenKey);
13+
const newKey = newKeys[nextProps.index];
1114

1215
if (oldKey === newKey) {
1316
displaySameSlide = true;

packages/react-swipeable-views-core/src/getDisplaySameSlide.test.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,4 +126,26 @@ describe('getDisplaySameSlide', () => {
126126

127127
assert.strictEqual(getDisplaySameSlide(oldState.props(), newState.props()), true);
128128
});
129+
130+
it('should work with dynamic children in arrays', () => {
131+
const oldState = mount(
132+
<SwipeableViews index={2}>
133+
<div key="1" />
134+
{['2', '3', '4'].map(k => (
135+
<div key={k} />
136+
))}
137+
</SwipeableViews>,
138+
);
139+
140+
const newState = mount(
141+
<SwipeableViews index={3}>
142+
<div key="1" />
143+
{['2', '3', '4'].map(k => (
144+
<div key={k} />
145+
))}
146+
</SwipeableViews>,
147+
);
148+
149+
assert.strictEqual(getDisplaySameSlide(oldState.props(), newState.props()), false);
150+
});
129151
});

0 commit comments

Comments
 (0)