title: Toggle button with blade components and alpine.js
body: <p>I'm trying to create my own toggle component. This component should just behave like a normal <code>&lt;input type=&quot;checkbox&quot; &gt;</code>. So far I've created the following:</p>
  <p>toggle.blade.php</p>
  <pre><code>@props([
      'id' =&gt; 1
  ])
  
  &lt;div class=&quot;flex justify-center items-center&quot;&gt;
      &lt;div {{ $attributes-&gt;whereStartsWith('class')-&gt;merge(['class' =&gt; 'relative rounded-full transition duration-200 ease-linear' ]) }}
          :class=&quot;[ $refs.toggle{{ $id }}.checked ? 'bg-green-400' : 'bg-gray-400' ]&quot;&gt;
          &lt;label for=&quot;toggle{{ $id }}&quot;
              class=&quot;absolute left-0 bg-white border-2 mb-2 w-1/2 h-full rounded-full transition transform duration-100 ease-linear cursor-pointer&quot;
              :class=&quot;[ $refs.toggle{{ $id }}.checked ? 'translate-x-full border-green-400' : 'translate-x-0 border-gray-400' ]&quot;&gt;&lt;/label&gt;
          &lt;input x-ref=&quot;toggle{{ $id }}&quot; type=&quot;checkbox&quot; id=&quot;toggle{{ $id }}&quot; class=&quot;appearance-none w-full h-full active:outline-none focus:outline-none&quot;
              {{ $attributes }} x-init=&quot;console.log('test')&quot; /&gt;
      &lt;/div&gt;
  &lt;/div&gt;
  </code></pre>
  <p>How I call it:</p>
  <pre><code>&lt;div&gt;
    &lt;x-inputs.toggle class=&quot;w-8 h-4&quot; value=&quot;{{ $permission['id'] }}&quot; 
      id=&quot;{{ $permission['id'] }}&quot; x-model=&quot;permissions&quot; /&gt; &lt;-- this one
    &lt;input class=&quot;form-checkbox&quot; value=&quot;{{ $permission['id'] }}&quot; type=&quot;checkbox&quot; x-model=&quot;permissions&quot;&gt;
  &lt;/div&gt;
  </code></pre>
  <p>I want to be able to put an x-model on my component. So that I can use the normal two-way binding from a checkbox input.</p>
  <p>The code above works, but because the ref (input) is later initialized than the <code>$refs</code> calls. Causing the wrong classes in the toggle, until one of the checkboxes/toggles is pressed (refs updated), see image:</p>
  <p><img src="https://i.stack.imgur.com/bboue.png" alt="Upload permission checkboxes/toggles" /></p>
  <p>Normally, I would just give the component an x-data and check if toggled, etc. But then I can't use the x-model because the model doesn't exist in the x-data property of the component.</p>
  <p>What I also tried is passing the value of the <code>x-model</code> in the class property like: <code>:class=&quot;[ {{ $attirubtes-&gt;whereStartsWith('x-model')-&gt;first() ? ... : ... ]&quot;</code>. But this doesn't work either, because I pass an array to the x-model checkbox, where alpine.js does some fancy things and handles it correctly.</p>
  <p>Any idea how I can solve this problem?</p>
  <p>Thanks in advance.</p>