1

Here is my example. How to call greeting() function from the button? Please help me, thanks!

---
import Layout from "@layouts/Layout.astro";
const greeting = () => {
  console.log("Hello, server");
};
---

<Layout title="Hello, world" class="pt-10">
  <h1>I'm wondering</h1>
  <button onclick="">Click me</button>
</Layout>
Thuong Vu
  • 53
  • 1
  • 7
  • 1
    It seems like you want a function to be ran on the server when a button is pressed. I fear that this is not possible in this way. For this to work, you would need to make a request to an [endpoint](https://docs.astro.build/en/core-concepts/endpoints/). You're also unable to define a function in the astro frontmatter and then reference it in the onclick event. For this to work, it should be below the frontmatter inside a script tag. For further help, I would reccomend joinging [the Astro discord](https://astro.build/chat) – Marijn Kneppers Jul 26 '23 at 19:36

1 Answers1

2

I don't believe this is possible with Astro.

The frontmatter is always processed on the server, whether at build or render (SSG or SSR). Frontmatter variables are serialized with JSON.stringify().

The button's onclick is processed on the client, and can only utilize functions already available on the client.

Astro docs recommend using addEventListener in a <script> tag for onclick functionality: https://docs.astro.build/en/guides/client-side-scripts/#handle-onclick-and-other-events

---
import Layout from "@layouts/Layout.astro";
---
<Layout title="Hello, world" class="pt-10">
  <h1>I'm wondering</h1>
  <button id="tgt">Click me</button>
</Layout>
<script>
  const tgt = document.querySelector("#tgt");
  tgt.addEventListener("click", () => {
    console.log("Hello, on client");
  });
</script>

If you'd like a form on the client to run a function on the server: https://docs.astro.build/en/recipes/build-forms/

BazCo
  • 21
  • 1