#All props work except handleClick function prop

2 messages · Page 1 of 1 (latest)

worldly merlin
#

index.astro:

<Secondary
  client:load
  props={{
    text: "My Work",
    handleClick: () => {
      window.location.href = "/projects";
    },
    size: "lg",
    align: "center",
    padded: false,
   }}
/>

All of these props are being passed as expected, however when I log the handleClick prop in the Secondary component directly, it returns as null.

Weirdly enough, this same component works when nested inside of Card.svelte, another svelte component which is rendered in index.astro:

        <SkillCard
          props={{
            title: "Svelte",
            description: "Svelte is cool",
            icon: {
              name: "blue-svelte-icon",
              type: "custom",
              href: "https://svelte.dev/",
            },
            endpoint: "/projects?skill=svelte",
            border: {
              color: "#3d6eff",
              caption: "Most Experience",
            },
          }}
          client:load
        />

^^^ this component renders the Secondary svelte component as a child, in which case its props work as expected.

proven drum
#

You can't pass down functions as props in Astro components
You can find a workaround in this discussion https://discord.com/channels/830184174198718474/1029086433694199818

Alternatively you could serialize your function in the frontmatter and construct a new function from that but know that using the Function constructor has similar security issues as eval
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/Function

Demo here https://stackblitz.com/edit/github-rf3tao?file=src%2Fcomponents%2FCounter.tsx,src%2Fpages%2Findex.astro&on=stackblitz

The Function() constructor creates a new Function object. Calling the constructor directly can create functions dynamically, but suffers from security and similar (but far less significant) performance issues as eval(). However, unlike eval (which may have access to the local scope), the Function constructor creates functions which execute in th...

Run official live example code for Astro Framework React, created by Withastro on StackBlitz