Change carousel items when items reload

master
Hasan Genc 4 years ago
parent 0c7936c900
commit 9763f23c7b
  1. 42
      __tests__/helpers.spec.tsx
  2. 9
      src/components/carousel/index.tsx
  3. 19
      src/helpers/index.ts

@ -82,9 +82,49 @@ describe('helpers', () => {
const oldNodes = reactNodes('old', 5) as Item[];
const newNodes = reactNodes('new', 6) as Item[];
const expected = reactNodes('new', 5) as Item[];
const infinite = true;
const slide = 5;
const result = helpers.updateNodes(oldNodes, newNodes);
const result = helpers.updateNodes(oldNodes, newNodes, slide, infinite);
expect(result).toEqual(expected);
});
it('should change nodes with new items when nodes not matched', async () => {
const oldNodes = reactNodes('old', 5) as Item[];
const infinite = true;
const slide = 2;
const newNodes = ([
{
key: 14,
props: '',
},
{
key: 15,
props: '',
},
] as unknown) as Item[];
const expectedNodes = ([
{
key: 14,
props: '',
},
{
key: 15,
props: '',
},
{
key: 14,
props: '',
},
{
key: 15,
props: '',
},
] as unknown) as Item[];
const result = helpers.updateNodes(oldNodes, newNodes, slide, infinite);
expect(result).toEqual(expectedNodes);
});
});

@ -32,7 +32,12 @@ export const Carousel: FunctionComponent<CarouselProps> = (userProps: CarouselPr
if (props.dynamic) {
React.useEffect(() => {
const newItems = updateNodes(items, userProps.children);
const newItems = updateNodes(
items,
userProps.children,
props.slide,
props.infinite,
);
setItems(newItems);
}, userProps.children);
}
@ -156,7 +161,7 @@ export interface CarouselProps {
className?: string;
useArrowKeys?: boolean;
a11y?: { [key: string]: string };
dynamic: boolean;
dynamic?: boolean;
}
export interface CarouselState {

@ -144,8 +144,23 @@ export function getOuterWidth(el: HTMLElement) {
);
}
export function updateNodes(oldItems: Item[], newItems: Item[]): Item[] {
return oldItems.map((oldItem) => {
export function updateNodes(
oldItems: Item[],
newItems: Item[],
slide: number,
infinite: boolean,
): Item[] {
const matchedItems = oldItems.map((oldItem) => {
return newItems.find((newItem) => oldItem.key === newItem.key) as Item;
});
if (areItemsNotMatched(matchedItems)) {
return initItems(newItems, slide, infinite);
}
return matchedItems;
}
export function areItemsNotMatched(items: Item[]): boolean {
return items.some((item) => item === undefined);
}

Loading…
Cancel
Save