Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

113
Vistas
Is it possible to create dynamic inline bindings with Alpine.js?

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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).

The hacky way

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>

The libraries

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>
A biased disclaimer

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda