Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion src/Overflow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,11 @@ function Overflow<ItemType = any>(
if (typeof itemKey === 'function') {
return itemKey(item);
}
return (itemKey && (item as any)?.[itemKey as keyof any]) ?? index;
return (
(itemKey !== undefined && itemKey !== null
? (item as any)?.[itemKey as keyof any]
: undefined) ?? index
);
},
[itemKey],
);
Expand Down
51 changes: 51 additions & 0 deletions tests/index.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react';
import Overflow from '../src';
import { OverflowContext } from '../src/context';
import { mount } from './wrapper';

interface ItemType {
Expand Down Expand Up @@ -114,6 +115,56 @@ describe('Overflow.Basic', () => {

expect(wrapper.findItems().text()).toEqual('Label 0');
});
it('supports falsy itemKey 0 and empty string', () => {
const errorSpy = jest
.spyOn(console, 'error')
.mockImplementation(() => {});

const seenZeroKeys: React.Key[] = [];
const KeyReader: React.FC<{
target: React.Key[];
children: React.ReactNode;
}> = ({ target, children }) => {
const ctx = React.useContext(OverflowContext);
target.push(ctx.itemKey);
return <Overflow.Item>{children}</Overflow.Item>;
};

const tupleData: [string, string][] = [
['k-0', 'Label 0'],
['k-1', 'Label 1'],
];
mount(
<Overflow<[string, string]>
data={tupleData}
itemKey={0}
renderRawItem={item => (
<KeyReader target={seenZeroKeys}>{item[1]}</KeyReader>
)}
/>,
);

expect(seenZeroKeys).toEqual(['k-0', 'k-1']);

const seenEmptyKeys: React.Key[] = [];
const emptyKeyData = [
{ '': 'e-0', label: 'Label 0' },
{ '': 'e-1', label: 'Label 1' },
];
mount(
<Overflow<{ '': string; label: string }>
data={emptyKeyData}
itemKey=""
renderRawItem={item => (
<KeyReader target={seenEmptyKeys}>{item.label}</KeyReader>
)}
/>,
);

expect(seenEmptyKeys).toEqual(['e-0', 'e-1']);
expect(errorSpy).not.toHaveBeenCalled();
errorSpy.mockRestore();
});
});

it('customize component', () => {
Expand Down