damycode
damycode

Reputation: 23

Using Alpine.js x-on events on Astro.js component

I'm trying to build some simple stuff with Astro.js for HTML templates and Alpine.js for interactivity when needed. I stumbled upon problem of trying to use Alpine x-on events on Astro component

Here is sample usage of the Button component:

  <div x-data>
    <Button @click="console.log('Clicked astro')">Click me</Button>
    <button @click="console.log('Clicked normal button')">Click me</button>
  </div>

The first one doesn't work while the native button works as normal.

Button component is just a button element with some tailwind classes, nothing fancy:

<button class="border-[1px] rounded-lg transition px-6 py-2 hover:text-inherit hover:border-transparent">
  <slot />
</button>

How can I get it to work? I really love astro with alpine so far but this little thing is stopping me from using it for my project.

I tried various of different things but none of them worked really. I went through docs and couldn't find anything related to my issue - it feels like there must a simple solution but I'm missing something.

Upvotes: 1

Views: 2299

Answers (1)

damycode
damycode

Reputation: 23

I have reached out to Astro support on discord and it was answered by user happydev there:

Anything passed to an astro component like this is taken as a prop, so you need to pass it to the element you want to bind the event on

Something like this

//Button.astro
---
const {"@click": click} = Astro.props
---
<button @click={click}>
  <slot/>
</button>

Upvotes: 0

Related Questions