Jane
Jane

Reputation: 157

How to solve unexpected number of root elements issue in alpine js?

I am working on functionality in alpine js where I need to add a radio button inside the template tag. Here is what I am doing.

<div class="customRadioStyle">
    <template x-for="name in record.names">
        <input type="radio" :value="name.value" :id="name.id">
        <label :for="name.id" x-text="name.value"></label>
    </template>
</div>

But this code gives me the following error.

Alpine: <template> tag with [x-for] encountered with an unexpected number of root elements. Make sure <template> has a single root element.

Is there any solution for this?

I check this link too but still not able to find a solution for this. https://github.com/alpinejs/alpine/issues/539

Any help would be appreciated.

Upvotes: 1

Views: 2041

Answers (1)

Danziger
Danziger

Reputation: 21191

Just do what the error says and make sure there's a single element inside the <template>. In you case, you can just add the <input> inside the <label> or wrap them both with a <div>:

window.MyComponent = () => ({
  names: [{
    id: 'name1',
    value: 'Name 1',
  }, {
    id: 'name2',
    value: 'Name 2',
  }, {
    id: 'name3',
    value: 'Name 3',
  }],
});
body {
  font-family: monospace;
}

label {
  display: flex;
  align-items: center;
  padding: 4px 0;
}

input {
  margin: 0 8px 0 0;
}
<div x-data="MyComponent()">
  <template x-for="name in names">
    <label :for="name.id">
      <input type="radio" :value="name.value" :id="name.id" name="radioGroup">
      <span x-text="name.value"></span>
    </label>
  </template>
</div>

<script src="https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.min.js"></script>

Note that in the event handler I'm still calling it e, but in the HTML I've used download($event) instead of download(e).

Upvotes: 1

Related Questions