Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

112
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!