1

I want to generate a list of custom components , composed of an input field and a few checkboxes:

<script>
const messages = [
 { id: "2fzae4", text: "aaaaa"},
 { id: "456ndr", text: "bbbbb"}

];

const tags = [
  { id: "01", label: "Twitter"},
  { id: "02", label: "Instagram"}
];
</script>

<ul>
{#each messages as msg (msg.id)}
  <li>
      <Ainput textField={msg.text} {tags}/>
  </li>
{/each}
</ul>

// This is a part of the <Ainput> component 

<div class="wrapper">
  <input type="text" bind:value={textField}/>
  <Tag {tags} />
</div>
// Tag component, a set of checkboxes
<script>
 export let tags;
</script>

<div>
 {#each tags as tag (tag.id)}
 <div>
   <checkbox id="{tags.id}"/>
   <label for="{tags.id}">{tags.label}</label>
 </div>
 {/each}
</div>

I need to pass down unique tag.id values in the array 'tags' on every iteration to make checkboxes work, but how to achieve this?

Tomasz Plonka
  • 285
  • 4
  • 12

1 Answers1

1

You don't need to do that. Check out this answer here. You can just put the <input> inside the <label>, then no id/for is needed:

<div>
 {#each tags as tag (tag.id)}
   <div>
     <label>
      <input type="checkbox"/>
      {tags.label}
     </label>
   </div>
 {/each}
</div>

Working demo:

<div>
  <label>
    <input type="checkbox">
    Click me, please!
  </label>
</div>
<div>
  <label>
    <input type="checkbox">
    No, click me instead!
  </label>
</div>
CherryDT
  • 25,571
  • 5
  • 49
  • 74
  • Hi, yes, this of course would be fine, but styling does not work when there are no ids assigned. – Tomasz Plonka Apr 23 '20 at 14:37
  • I don't understand. Why? – CherryDT Apr 23 '20 at 14:38
  • Also, you could just assign random IDs to the `tag` elements in the array and use those afterwards. – CherryDT Apr 23 '20 at 14:38
  • @CherryT: Oh, sorry, my styles use "+" combinator, so they got messed up when when inside – Tomasz Plonka Apr 23 '20 at 14:44
  • Ah; in that case I think just reordering your style selector would fix it, and it'd probably be the easiest and cleanest way to do it without IDs :) – CherryDT Apr 23 '20 at 14:45
  • 4
    This is not a complete answer, sometimes you may want a label and input to be in different places, and [explicit for=id labels are better for accessibility tools](https://css-tricks.com/html-inputs-and-labels-a-love-story/#how-to-pair-a-label-and-an-input). – Mingwei Samuel Jul 05 '21 at 17:45
  • Also accessibility-wise, ARIA attributes often need to refer to other elements by their IDs. For instance, ` aria-controls` or `aria-labelledby`. – GnxR Jul 14 '21 at 08:32
  • Another use case that is not answered by this is the `name` attribute on `input[type="radio"]`. – simon Oct 02 '21 at 00:18