I have an array that contains other arrays:
export const ArtifactArray = [
AccessoriesArtifacts,
BodyArtifacts,
CloakArtifacts,
FeetArtifacts,
HandsArtifacts,
HeadArtifacts,
LeftHandArtifacts,
MainHandArtifacts,
NeckArtifacts
]
Each of these arrays contain objects:
export const BodyArtifacts = [
WonderArmor,
BrimstoneBreastplate,
PetrifiedWoodBreastplate,
DragonScaleArmor,
RibCage,
GreatBasilistScales,
TitansCuirass,
CyclopsKingTunic,
];
Later on I’m iterating through the array and displaying all of these objects on the screen like this:
{ArtifactArray.map((array, index) => (
<Fragment key={index}>
{array.map((artifact, index) => (
<ArtifactsBlock
key={index}
src={artifact.pic}
name={artifact.name}
/>
))}
</Fragment>
))}
Everything works as expected.
Then I’m trying to add a pagination to it, and that’s where the problem begins. I want to return only 20 objects per page (120 in total). But how do I do that if those arrays don’t have the same number of objects in each? If I use array.slice(0, 20), array.slice(20, 40), etc. by the end of some of those arrays it will return 11 or 9 instead. Of course I could get rid of those inner arrays and simply lump all objects into one array, but that’s clunky as hell. I’d like to keep it the way it is now.
2
Answers
How about flattening your list?
You can flatten the arrays of objects down to one array, and then use the length of that array plus a "limit" of the number of items to show to determine how you’re going to slice your data.
Here’s a small working example which uses a small dataset (a total of eleven items). The data is flattened and passed into the component. There are two states: one for the page, and one for the limit. Note: here the limit is set to two items per page.
When the component is rendered it calls both the
getPages
andgetArtifacts
functions. They build both a series of page buttons, and an array of artifacts using the information in the page and limit states.