1.0.1 • Published 10 months ago
element-map v1.0.1
ElementMap
ElementMap
is a lightweight utility component for React that simplifies mapping over an array of items and rendering elements. It wraps React's Children.toArray()
method to provide a consistent key for rendered elements, ensuring that each child element gets a unique key when mapping.
Features
- Simple API: Takes an array of items and a render function to generate React elements.
- Optimized for Lists: Uses React's
Children.toArray()
to ensure proper key handling. - Minimal and Flexible: Allows you to render any type of content.
Installation
You can install the package via npm or yarn:
# Using npm
npm install element-map
# Using yarn
yarn add element-map
Usage
Here’s how you can use ElementMap
in your React application:
Example 1: Basic Usage with a List
import React from "react";
import { ElementMap } from "element-map";
const items = ["Apple", "Banana", "Cherry"];
const MyComponent = () => (
<div>
<ElementMap
of={items}
render={(item, index) => <div key={index}>{item}</div>}
/>
</div>
);
export default MyComponent;
Example 2: Rendering Custom Components
You can also render custom components by passing a function to the render
prop.
import React from "react";
import { ElementMap } from "element-map";
const products = [
{ id: 1, name: "Laptop", price: "$999" },
{ id: 2, name: "Smartphone", price: "$799" },
{ id: 3, name: "Tablet", price: "$499" }
];
const ProductCard = ({ product }) => (
<div>
<h2>{product.name}</h2>
<p>{product.price}</p>
</div>
);
const ProductList = () => (
<div>
<ElementMap
of={products}
render={(product) => <ProductCard key={product.id} product={product} />}
/>
</div>
);
export default ProductList;
Props
of
(required): An array of items you want to map over.render
(required): A function that takes each item and its index and returns a React element. The render function signature is(item, index) => ReactNode
.
Example 3: Working with Complex Data
For more complex data structures, ElementMap
is flexible enough to render custom layouts or components.
import React from "react";
import { ElementMap } from "element-map";
const posts = [
{ id: 1, title: "First Post", content: "This is the first post" },
{ id: 2, title: "Second Post", content: "This is the second post" },
{ id: 3, title: "Third Post", content: "This is the third post" },
];
const PostItem = ({ post }) => (
<div>
<h2>{post.title}</h2>
<p>{post.content}</p>
</div>
);
const Blog = () => (
<div>
<ElementMap
of={posts}
render={(post) => <PostItem key={post.id} post={post} />}
/>
</div>
);
export default Blog;
Why Use ElementMap
?
- Consistent key handling : Automatically converts mapped elements to an array, ensuring proper key assignment.
- Reusable : Ideal for rendering dynamic lists or arrays in any React component.
- Lightweight : Adds minimal overhead to your project and requires no additional libraries other than React.