Reputation: 175
So I have this button, and x-data for a parent div had this: days: {SUN: false}. It finds the variable so no problem. Here is the button:
<button type="button" class="date-btn" @click="days[$el.textContent] = !days[$el.textContent]; alert(days[$el.textContent])" :class="{'bg-blue-800' ? days[$el.textContent]: ''}">SUN</button>
The alert shows that the value switches from true and false on click, but the color of the button never changes.
Here is my .date-btn styles, but even stripping it dry except of m
and px
gives the same result:
@layer components {
.date-btn {
@apply m-2 px-7 py-3 text-white font-medium text-sm leading-snug
uppercase rounded shadow-md hover:shadow-lg
focus:shadow-lg focus:outline-none focus:ring-0
active:shadow-lg transition duration-150 ease-in-out drop-shadow-lg;
}
}
I also did :class="'bg-blue-800' ? days[$el.textContent]: ''"
but no banana.
What is wrong with my :class call?
Upvotes: 0
Views: 1565
Reputation: 175
This worked :class="{'bg-blue-800' : days[$el.textContent]}"
Notice it's a boolean, if days[$el.textContent]
is true or 1, then the class is active. Otherwise it is false or 0, so class is inactive. This is also easy to extend and read for other classes you want to add.
Shoutout to https://daily.dev/blog/alpine-js-the-ultimate-guide
Upvotes: 0
Reputation: 2480
I'd have a read in the docs. x-bind
, what is what you're using when using the shorthand :class
, uses booleans to define what class to bind. As per example you've given, you've mixed up the ternary statement and object syntax. This won't ever result in anything. However, say you hadn't wrapped it in an object, then it would still fail, since 'bg-blue-800'
is always truthy, which will always bind ''
as class.
If you want to use a ternary statement, instead you'd have to write it as such: :class="days[$el.textContent] ? 'bg-blue-800' : ''"
.
Because AlpineJS aims at making life easy, you can also use shorthand syntax to replace the ternary operator. In this case, you could rewrite above example to :class="days[$el.textContent] && 'bg-blue-800'"
The last method you already mention in your own answer. The object class: boolean
syntax, which (in my opinion) is the most logical way to write the x-bind
is the last possible method to bind elements with. By passing a class as key, and a boolean as value, AlpineJS knows which class(es) to bind.
Upvotes: 1
Reputation: 10502
The input of the ternary operator should be a condition:
:class="days[$el.textContent] ? 'bg-blue-800' : ''"
You can also use a shorthand version:
:class="days[$el.textContent] && 'bg-blue-800'"
Upvotes: 1