The client:click
directive hydrates the component when clicking on it or when the specified element is clicked.
Setup
For setting up the directive, include the integration in your Astro project.
- Install the library using your preferred package manager:
npm i -D @astro-tools/client-directives
- Add the integration to your project configuration:
astro.config.mjs import { defineConfig } from 'astro/config';import { clickClientDirective } from '@astro-tools/client-directives/click';export default defineConfig({integrations: [clickClientDirective()],});
With client:on directive
To integrate this directive with the client:on
, configure the directive as follows:
import { defineConfig } from 'astro/config';
import { onClientDirective } from '@astro-tools/client-directives/on';
export default defineConfig({ integrations: [ onClientDirective({ directives: [ { name: 'click', entrypoint: '@astro-tools/client-directives/click/directive', }, ], }), ],});
Use
Add the directive as attribute of the component to hydrate:
<MyComponent client:click />
When clicking in any part of the component, the component will be hydrated and the event will be replayed using the target of the initial event.
---import Square from '@/libs/examples/Square.svelte';
interface Props { id: string;}
const { id } = Astro.props;---<Square {id} text="Click me!" client:click />
<script lang="ts">import { notifyHydration } from '@/libs/examples/hydration';import { onMount } from 'svelte';
export let id: string;export let text: string;
let hydrated = false;
onMount(() => { hydrated = true; notifyHydration(id);});</script>
<button type="button" class="square" class:square--hydrated={hydrated} on:click={() => text = 'Clicked!'}> {text}</button>
<style lang="scss"> @use './Square.scss';</style>
With an element trigger
Add the directive as attribute of the component to hydrate with a valid query selector:
<button id="my-trigger">Hydrate!</button><MyComponent client:click="#my-trigger" />
When clicking the element target, the component will be hydrated. In this case, the event replay won’t be done.
---import Square from '@/libs/examples/Square.svelte';
interface Props { id: string;}
const { id } = Astro.props;---<button id="click-directive-trigger">Click to Hydrate!</button><hr/><Square {id} text="Hydrate me!" client:click="#click-directive-trigger" />
<script lang="ts">import { notifyHydration } from '@/libs/examples/hydration';import { onMount } from 'svelte';
export let id: string;export let text: string;
let hydrated = false;
onMount(() => { hydrated = true; notifyHydration(id);});</script>
<button type="button" class="square" class:square--hydrated={hydrated} on:click={() => text = 'Clicked!'}> {text}</button>
<style lang="scss"> @use './Square.scss';</style>