Skip to content

Client directive: Event

The client:event directive hydrates the component when the specified event is sent through the window object.

Setup

For setting up the directive, include the integration in your Astro project.

  1. Install the library using your preferred package manager:
    npm i -D @astro-tools/client-directives
  2. Add the integration to your project configuration:
    astro.config.mjs
    import { defineConfig } from 'astro/config';
    import { eventClientDirective } from '@astro-tools/client-directives/event';
    export default defineConfig({
    integrations: [eventClientDirective()],
    });

With client:on directive

To integrate this directive with the client:on, configure the directive as follows:

astro.config.mjs
import { defineConfig } from 'astro/config';
import { onClientDirective } from '@astro-tools/client-directives/on';
export default defineConfig({
integrations: [
onClientDirective({
directives: [
{
name: 'event',
entrypoint: '@astro-tools/client-directives/event/directive',
},
],
}),
],
});

Use

Add the directive as attribute of the component to hydrate with the event name to listen:

<MyComponent client:event="my-custom-event" />

Remember that the event must be sent using dispatchEvent method because the communication is being done using the window object.

---
import Square from '@/libs/examples/Square.svelte';
interface Props {
id: string;
}
const { id } = Astro.props;
---
<button id="event-directive-btn">Click to dispatch the event!</button>
<hr/>
<Square {id} text="Click me!" client:event="my-custom-event" />
<script>
document.getElementById('event-directive-btn')!.addEventListener('click', () => {
dispatchEvent(new CustomEvent('my-custom-event'));
});
</script>
Preview Static