Iterator
A component that iterates over a given array and renders each item.
When a string is passed as itemKey, the value of that property on each element is used as its unique key.
For arrays of strings or numbers, keys are automatically assigned in the format ${item}_${index} even without specifying itemKey.
Code
Interface
typescript
interface IteratorProps<T> {
items: T[] | readonly T[] | undefined;
itemKey?: T extends Record<PropertyKey, any> ? keyof T : string;
renderItem: (item: T, index: number) => JSX.Element;
}
const Iterator: <T>({
items,
itemKey,
renderItem,
}: IteratorProps<T>) => JSX.Element;
Props
| Name | Type | Default | Description |
|---|---|---|---|
items | T[] | readonly T[] | undefined | - | Array to iterate and render |
itemKey | keyof T | string | - | Property name to use as the unique key for each element |
renderItem | (item: T, index: number) => JSX.Element | - | Function to render each item |
Usage
typescript
import { Iterator } from '@modern-kit/react';
interface Item {
id: number;
name: string;
}
const Example = () => {
const items: Item[] = [
{ id: 1, name: 'Gromit' },
{ id: 2, name: 'Dylan' },
{ id: 3, name: 'Minjae' },
];
return (
<Iterator
itemKey="id"
items={items}
renderItem={(item) => (
<h3>
id: {item.id}, name: {item.name}
</h3>
)}
/>
);
};