I need a component that, given some children, it will repeat this children over and over to fill the screen. Let's say it has a simple markdown like this:
<FillScreen items={[
{ id: 'one', content: 'foo' },
{ id: 'two', content: 'bar' }
]} />
Internally, this component will get the screen size, and will eventually fill the screen with these items. The resulting DOM will look like this:
<div class="fill-screen">
<div>foo</div>
<div>bar</div>
<div>foo</div>
<div>bar</div>
<div>foo</div>
<div>bar</div>
<div>foo</div>
</div>
The problem I have is that when this element has calculated that it needs to render 7 elements, I can't directly use items[i].id as a key for each element because there will be repeated keys.
I'm not sure what's the best pattern for this problem, I've thought two possible solutions which I don't fully like:
Solution A
Append a loop index on every key, so the array in render contains the following JSX:
<div key='one-0'>foo</div>
<div key='two-0'>bar</div>
<div key='one-1'>foo</div>
<div key='two-1'>bar</div>
<div key='one-2'>foo</div>
<div key='two-2'>bar</div>
<div key='one-3'>foo</div>
Edit - note that these elements are being generated into an array, that's why we need to specify a key
I see two issues with this approach:
- At this point I may just get rid of the original key and just use an index, something that's absolutely discouraged.
- My real-life component, the way you give items to this component is through children (I oversimplified in here to get the point across), so I would have to clone each element just to change the key.
Solution B
Use fragments to separate between loops
<Fragment key={0}>
<div key='one'>foo</div>
<div key='two'>bar</div>
</Fragment>
<Fragment key={1}>
<div key='one'>foo</div>
<div key='two'>bar</div>
</Fragment>
<Fragment key={2}>
<div key='one'>foo</div>
<div key='two'>bar</div>
</Fragment>
<Fragment key={3}>
<div key='one'>foo</div>
</Fragment>
In here it feels more clean, but at the same time this is not the reason Fragments were added in the first place, so maybe it's misusing them?.
Is there a better solution to this problem? What's the community standard?