#Passing a prop to a script

8 messages · Page 1 of 1 (latest)

verbal wasp
#

Hello 👋 , I'm trying to pass a prop to the <script tag in a component.

Here is the component.astro:

---
interface Props {
  containerName: string
}
const { containerName } = Astro.props as Props
---

<div class={containerName}></div>

<script>
  console.log({ containerName })
</script>

In the console, the error is "Uncaught ReferenceError: containerName is not defined". Any hint on how to make this work? Thanks a lot!

golden moss
verbal wasp
#

Thank you 🙏

golden moss
#

Feel free to ping me if you have more questions about it! That's a tricky part of Astro

#

Sorry about the DM but please ask here! It's easier as other support members can help and it's also useful for future people searching for similar issues

verbal wasp
#

Oh no worries!

I'm building an interactive article (.mdx file) and have a few questions that might not be directly related to the issue:

  • I'm currently using Vanilla JS to write the demos JS (simple stuff like toggling a class, hiding an element.. etc). Will the issue be solved by default if I used React, for example?
  • Is it possible to scope the <script> for its component, and avoid interfering with other parts of the page?
golden moss
#

it's true that this approach pollutes the global namespace so there could be conflicts between components. I think that using a ui framework and passing your prop to it will solve both issues

verbal wasp
#

Good to know! I will try a using a UI framework. Thanks again.