title: Get index of each component in Svelte slot
body: <p>Is there a way to loop through all the children in a Svelte component?</p>
  <h2>Goal</h2>
  <p>I'm working on creating a list component in Svelte with this syntax (ideally).</p>
  <pre><code>&lt;List&gt;
    &lt;ListItem&gt;Item 1&lt;/ListItem&gt;
    &lt;ListItem&gt;Item 2&lt;/ListItem&gt;
    &lt;ListItem&gt;Item 3&lt;/ListItem&gt;
  &lt;/List&gt;
  </code></pre>
  <p>However, the list should have quite a bit of interactivity.</p>
  <ul>
  <li>Users should be able to click on an item and select it</li>
  <li>Only the first item should be tabbable (<code>tabindex={0}</code>)</li>
  <li>Users should be able to use arrow keys / enter key to select a list item</li>
  <li>+more that's not relevant to the question</li>
  </ul>
  <p>Check out the <a href="https://material-components.github.io/material-components-web-catalog/#/component/list" rel="nofollow noreferrer">Material Design web components for demos</a>.</p>
  <h2>Issue</h2>
  <p>To do this, elements need to know their &quot;position&quot; in the list. For instance, the first list item needs to know that it's the first to set the correct <code>tabindex</code>. And to use arrow keys to navigate the list, you need to know &quot;Item 2 is active&quot; to switch to &quot;Item 3&quot; on arrow down.</p>
  <p>Is there a way to loop through all the children in a component?</p>
  <p>Or alternatively, a way to achieve the Material Design list behavior through composition?</p>
  <p><em>I know it's possible to achieve this by using a data prop instead of composition. But for my use case, composition will likely be much better in the long run.</em></p>
  <h2>React equivalent</h2>
  <p>If you're familiar with React, I looking for something that works like this incredibly simplified example.</p>
  <pre><code>const List = (props) =&gt; {
    return (
      &lt;ul&gt;
        {React.Children.forEach(props.children, (child, index) =&gt; (
          child.props.tabIndex = index === 0 ? 0 : -1
        ))}
      &lt;/ul&gt;
    )
  }
  
  const ListItem = (props) =&gt; {
    return &lt;li tabIndex={props.tabIndex}&gt;{props.children}&lt;/li&gt;
  }
  </code></pre>