0

Case: Render the Button component 5 times

<script>
  const timesToBeRendered = 5;
</script>

<Button/> //Render this component x (5) times
rohanharikr
  • 1,201
  • 1
  • 13
  • 28
  • Similar to https://stackoverflow.com/questions/58213585/svelte-3-how-to-loop-each-block-x-amount-of-times – unloco Nov 13 '20 at 20:40

2 Answers2

2

You can do it using svelte each

<script>
  import Button from './Button.svelte'
  const timesToBeRendered = 5;
</script>

{#each Array(timesToBeRendered) as _, index}
  <Button key={index} />
{/each}

Repl

Thomas Hennes
  • 9,023
  • 3
  • 27
  • 36
unloco
  • 6,928
  • 2
  • 47
  • 58
0

new Array(timesToBeRendered).fill(0) will create an empty array with N 0's, that you can loop over. (yes the fill is required)

new Array(timesToBeRendered).fill(0).map((_, i)=><Button key={i}/>) will return a list of components, which react renders as siblings.

Dont forget key otherwise react cannot distinguish between the elements!

Gabriel Petersson
  • 8,434
  • 4
  • 32
  • 41