I would like to create a dynamic :class or :style binding that uses data stored in an Alpine.js variable.
<div x-data="{ divClass: 'inner', color: 'red' }">
<div :class="${divClass}"
:style="background-color: ${color}"></div>
</div>
In the example above, I would like the divClass variable to output a dynamic class inner, and the color to output a dynamic style red — is it possible?
As of August 2021, it is not possible to do it directly. However, there are two possible solutions (mentioned in this issue, in the Alpine.js repository).
There is a simple hack you can use to achieve what you want, you simply need to wrap the values of the attributes in backticks:
<div x-data="{ divClass: 'inner', color: 'red' }">
<div :class="`${divClass}`"
:style="`background-color: ${color}`"></div>
</div>
There are two libraries that help wrap dynamic classes/styles in a nice-looking code. They are classnames and stylenames. With them on board, the code could look something like this:
<div x-data="{ divClass: 'inner', color: 'red' }">
<div :class="classNames( divClass )"
:style="styleNames({ backgroundColor: color })"></div>
</div>
In my opinion, the first solution is better as it saves precious kB by not adding additional dependencies. However, you need to take into consideration that it's slightly less legible and potentially confusing for other developers.