#use component script variable in script tag
3 messages · Page 1 of 1 (latest)
Hi @tulip jay. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:
To use a component script variable like foo from Astro.props in a <script> tag, you can use the define:vars directive. This allows you to pass server-side variables from your component frontmatter into the client-side script. Here's how you can modify your code to make it work:
---
const { foo } = Astro.props;
---
<script define:vars={{ foo }}>
console.log(foo);
</script>
This approach uses the define:vars directive to pass the foo variable from the component script to the client-side script Script & Style Directives (https://docs.astro.build/en/reference/directives-reference/#definevars).
However, it's important to note that using define:vars on a <script> tag implies the is:inline directive, which means your script won't be bundled and will be inlined directly into the HTML Script & Style Directives (https://docs.astro.build/en/reference/directives-reference/#definevars).
If you need to pass multiple variables, you can do so by including them in the object passed to define:vars:
---
const { foo, bar, baz } = Astro.props;
---
<script define:vars={{ foo, bar, baz }}>
console.log(foo, bar, baz);
</script>