title: AlpineJS: How can I add a class to an element conditionally?
body: <p>I have an array of messages being pulled into view thanks to Laravel Echo, Livewire, and AlpineJS.</p>
  <pre><code>&lt;div class=&quot;mt-4 rounded-lg p-6&quot;
      x-data=&quot;{{ json_encode(['messages' =&gt; $messages, 'messageBody' =&gt; '']) }}&quot;
      x-init=&quot;
          Echo.join('demo')
          .listen('MessageSentEvent', (e) =&gt; {
              @this.call('incomingMessage', e)
          })
  &quot;&gt;
      &lt;template x-if=&quot;messages.length &gt; 0&quot;&gt; 
          &lt;template
              x-for=&quot;message in messages&quot;
              :key=&quot;message.id&quot;
          &gt;
              &lt;div class=&quot;my-8&quot;&gt;
                  &lt;div class=&quot;flex flex-row justify-between border-b border-gray-200&quot;&gt;
                      &lt;span class=&quot;text-white-600 chat-block-author&quot;  x-text=&quot;message.user.name&quot;&gt;&lt;/span&gt;: &lt;span class=&quot;text-white-800&quot; x-text=&quot;message.body&quot; style=&quot;margin-left:10px;&quot;&gt;&lt;/span&gt;
                  &lt;/div&gt;
              &lt;/div&gt;
          &lt;/template&gt;
      &lt;/template&gt;
  &lt;/div&gt;
  </code></pre>
  <p>I want to dynamically add a class called <code>chat-block-author</code> when the rendered message belongs to the logged-in user. The <code>Message</code> model does contain <code>user_id</code> for each item, but I can't seem to get AlpineJS to play well with conditional logic like I could with Blade.</p>
  <p>Any tips?</p>
  <p>This does not work</p>
  <pre><code>&lt;template x-if=&quot;message.user_id == {{ Auth::user()-&gt;id }}&quot;&gt;
      &lt;div class=&quot;my-8&quot;&gt;
          &lt;div class=&quot;flex flex-row justify-between border-b border-gray-200&quot;&gt;
              &lt;span class=&quot;text-white-600 chat-block-author&quot;  x-text=&quot;message.user.name&quot;&gt;&lt;/span&gt;: &lt;span class=&quot;text-white-800&quot; x-text=&quot;message.body&quot; style=&quot;margin-left:10px;&quot;&gt;&lt;/span&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  &lt;/template&gt;
  </code></pre>
  <p>as it produces this error</p>
  <pre><code>Uncaught (in promise) ReferenceError: message is not defined
      at eval (eval at tryCatch.el.el (alpine.js?df24:1), &lt;anonymous&gt;:3:36)
      at tryCatch.el.el (alpine.js?df24:140)
      at tryCatch (alpine.js?df24:127)
      at saferEval (alpine.js?df24:135)
      at Component.evaluateReturnExpression (alpine.js?df24:1747)
      at eval (alpine.js?df24:1714)
      at Array.forEach (&lt;anonymous&gt;)
      at Component.resolveBoundAttributes (alpine.js?df24:1696)
      at Component.updateElement (alpine.js?df24:1672)
      at eval (alpine.js?df24:1628)
  </code></pre>