#use component script variable in script tag

3 messages · Page 1 of 1 (latest)

tulip jay
#

e.g. this does not work

---                                     
const { foo } = Astro.props;            
---                                     
<script>console.log({foo})</script>     
                                        

how can i use foo in my script?

verbal belfryBOT
#

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>

Remember that this method is best suited for small amounts of data. For larger datasets or more complex scenarios, you might want to consider alternative approaches, such as using data-* attributes to store the values in your HTML output and then reading them in your script Pass frontmatter variables to scripts (https://docs.astro.build/en/guides/client-side-scripts/#pass-frontmatter-variables-to-scripts).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: