๐ง What Are slice()
and map()
in JavaScript?
slice(start, end)
: Returns a shallow copy of a portion of an array. It does not modify the original array.map(callback)
: Creates a new array by calling a function on every element of the original array.
These two methods are commonly used together in React to display a portion of an array, such as for pagination, previews, or "Show More" functionality.
โ
Basic Syntax in TypeScript (TSX)
tsx
const items: string[] = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
return (
<ul>
{items.slice(0, 3).map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
Output:
โ
You're displaying only the first 3 items of the array.
๐งฉ Full Example in a React Functional Component
tsx
import React from 'react';
type Product = {
id: number;
name: string;
};
const products: Product[] = [
{ id: 1, name: 'Laptop' },
{ id: 2, name: 'Phone' },
{ id: 3, name: 'Tablet' },
{ id: 4, name: 'Monitor' },
{ id: 5, name: 'Keyboard' },
];
const ProductList: React.FC = () => {
const visibleProducts = products.slice(0, 3); // Only show the first 3
return (
<div>
<h2>Top Products</h2>
<ul>
{visibleProducts.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</div>
);
};
export default ProductList;
๐๏ธ Common Use Cases in React + TSX
Use CaseExamplePaginationShow a fixed number of items per page using slice(start, end)
PreviewsDisplay only a portion of the data (slice(0, 5).map(...)
)โLoad MoreโUse slice(0, visibleCount)
to load more on button clickFiltering DisplayChain filter()
before slice()
to control visible content
๐ง TypeScript Tip
TypeScript ensures type safety during the .map()
phase:
tsx
products.slice(0, 3).map((product: Product) => (
<div key={product.id}>{product.name}</div>
));
Always ensure you use a unique key
propโpreferably something stable like an ID.
โ ๏ธ Common Mistakes to Avoid
MistakeFixUsing index
as key
when array changes dynamicallyUse a unique identifier (id
) insteadNot slicing before mapping when only partial data is neededCall slice()
before map()
Forgetting return in .map()
Use arrow function with {}
and explicit return
or () => (<JSX>)
๐ With Pagination Logic
tsx
const currentPage = 1;
const itemsPerPage = 3;
const start = (currentPage - 1) * itemsPerPage;
const end = start + itemsPerPage;
const pagedItems = items.slice(start, end);
๐ Summary
- โ
Use
.slice(start, end)
to extract a portion of an array. - โ
Use
.map()
to render each item into JSX. - โ
Combine both for controlled rendering in React TypeScript apps.
- ๐ TypeScript ensures type-safe mapping.
- ๐ Great for pagination, previews, and slicing large lists.