Search code examples
astrojs

How to add a simple onClick function callback to a astro component?


I would love to know how to do a simple astro component with a callback function onClick

my Button.astro component:

---
type Props = {
  title: string;
  className?: string;
  id: string;
  onClick?: () => void;
};
const { title, className, id, onClick } = Astro.props;
---

<!-- type==module faz com que o script só seja executado quando o DOM for inicializado. Isso dispensa ter que colocar a tag script abaixo do html -->
<button id={id} title={title} class={className}>
  <span class="sr-only">{title}</span>
  <slot />
</button>

<script define:vars={{ id, onClick }} type="module">
  console.warn("id", id, onClick, document.querySelector("#" + id));

  document.getElementById(id).addEventListener("click", onClick);
</script>

use:

<Button
    title="title"
    id="test-button"
    onClick={() => console.log("encontrou o elemento")}
  >
    Clique-me!
  </Button>

it keeps saying that onClick is undefined on browser console.

OBS: I am using the Button in a component that has client:load directive

I am using typescript. I dont want to add to the window a global function and neither pass a plain text to call a global function.

I would love to do a simple onClick callback like any other framework.

How it is possible? Thanks in advance


Solution

  • From the docs:

    In Astro components, the code in the frontmatter between the --- fences runs on the server and is not available in the browser.

    Astro components are server-side, which means they operate/run in a server context. Whatever you pass to them (which you will receive in the frontmatter) is coming from a server context.

    When it comes to functions, Astro will not be able to serialize server functions to client ones. You'll have to integrate a UI framework to be able to pass functions props to the client.