Skip to content

Instantly share code, notes, and snippets.

@ipetinate
Created April 10, 2023 19:27
Show Gist options
  • Save ipetinate/4d040156f4ee5211952a028ba2cb4982 to your computer and use it in GitHub Desktop.
Save ipetinate/4d040156f4ee5211952a028ba2cb4982 to your computer and use it in GitHub Desktop.
For component implementation, to abstract data map iteration inside components
// For.tsx
import { Key } from "react";
type TypeWithKey<T> = T & { key: Key };
type ForProps<T> = {
data: TypeWithKey<T>[];
each: (x: TypeWithKey<T>, key: Key) => JSX.Element;
};
export function For<T>({ data, each }: ForProps<T>) {
return data ? <>{data.map((item) => each(item, item.key))}</> : null;
}
// People.tsx
type Person = {
name: string;
age: number;
key: Key;
};
export function People() {
const people: Person[] = [
{ key: "p1", age: 23, name: "Daniel" },
{ key: "p2", age: 25, name: "Felipe" },
{ key: "p3", age: 30, name: "Gabriel" },
];
return (
<For
data={people}
each={(person, key) => <Person person={person} key={key} />}
/>
);
}
// Person.tsx
function Person({ person }: { person: Person }) {
return (
<div>
<p>{person.name}</p>
<p>{person.age}</p>
</div>
);
}
@ipetinate
Copy link
Author

ipetinate commented Apr 27, 2023

Uma sugestão para tornar o componente mais performático, é utilizar o React.memo() :

import { memo } from "react"

interface Props<T> {
  data?: T[]
  render: (item: T, index: number) => JSX.Element
  fallback?: JSX.Element | null
}

function FlatMap<T>({ data, render, fallback = null }: Props<T>) {
  return data && data.length > 0 ? <>{data.map(render)}</> : fallback
}

export default memo(FlatMap)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment