Skip to content
Bryce Russell edited this page Feb 20, 2023 · 5 revisions

Similar to using .map() but customizable using slots, can also loop x number of times

Features

  • Target index for alternative render using slots
  • Use negative indexes to target end of array
  • Access item in array as slot function argument
  • Makes loops easier
  • Nested mapping is easier

When do I use this?

Use this component when your trying to use .map() but want to target different indexes for alternative render, or you want to loop x number of times

How to Use

<For {...['one', 'two', 'three']}>
    {i => <li>{i}</li>}
</For>
<li>one</li>
<li>two</li>
<li>three</li>

Examples

Props

{...any[]}

Example

This component expects an array to be spread over its props like:

<For {...[1, 2, 3]}>

Note: You cannot use the loop prop when using spread syntax <For {...[]}>

loop?: number

Example

Loop x number of times, returns current index as slot argument

Note: You cannot use the spread syntax <For {...[]}> when using the loop prop

Slot Arguments

Example

Access current value in array using slot function arguments

interface Arguments {
    value: any;
    index: number;
    array: any[];
}
<For {...['one', 'two', 'three']}>
    {(value, index, array) => ...}
</For>

Slots

default

Default/fallback render if no slot is defined

[number]

Example

Target an index in passed array using a number as a named slot

Use negative numbers to target the end of the array (-1 targets last item in array)

Examples

Basic example

<For {...['one', 'two', 'three']}>
    {i => <li>{i}</li>}
</For>
<li>one</li>
<li>two</li>
<li>three</li>

Using loop prop

<For loop={3}>
    {i => <li>{i}</li>}
</For>
<li>0</li>
<li>1</li>
<li>2</li>

Target an index using a named slot

<For {...['one', 'two', 'three']}>
  {i => <li>{i}</li>}
  <second slot="1">
    {i => <li>{i} (Second)</li>}
  </second>
</For>
<li>one</li>
<li>two (Second)</li>
<li>three</li>

Target end of array using negative named slots

<For {...['one', 'two', 'three']}>
  {i => <li>{i}</li>}
  <last slot="-1">
    {i => <li>{i} (last)</li>}
  </last>
</For>
<li>one</li>
<li>two</li>
<li>three (last)</li>

Nested mapping

<For {...['one', 'two', 'three']}>
  {i => <li>
    {i}
    <ul>                       
      <For {...i}>
        {i => <li>{i}</li>}
      </For>
    </ul>
  </li>}
</For>