Created
April 10, 2023 19:27
-
-
Save ipetinate/4d040156f4ee5211952a028ba2cb4982 to your computer and use it in GitHub Desktop.
For component implementation, to abstract data map iteration inside components
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uma sugestão para tornar o componente mais performático, é utilizar o
React.memo()
: