Search code examples
javascriptastrojs

Passing a click handler into a client loaded React component does not work


Why doesn't this work?

index.astro

const handleClick = () => console.log("clicked");
---
<Button client:load onClick={handleClick}>bla</Button>

The button is from Shadcn. Looking at the Astro dev tool in the browser. I see this

{
  "onClick": null
}

I know that values in the front matter can be passed into the props of framework components. Then why not functions?


Solution

  • I know that values in the front matter can be passed into the props of framework components. Then why not functions?

    It's because these props are serialized to attributes in the HTML that's sent to the browser. Imagine calling JSON.stringify on a function. It's not going to work.

    The client-side JavaScript then reads out these props (basically JSON.parse and passes them to the island-framework, e.g. React.)