0

I have the following Astro component:

   ---
    type Props = {
      uuid: string;
    };
    
    const { uuid } = Astro.props;
    ---
    
    <div class="my-feature" data-uuid={uuid} id="my-feature"></div>
    
    <script is:inline src={import.meta.env.MY_SCRIPT}></script>
    
    <script>
      import { MyFeatureHelper } from '@/scripts/my-helper';
    
      let myFeature;
    
      const ref = document.getElementById('my-feature');
    
      myFeature = new MyFeatureHelper(ref as HTMLDivElement, {
        uuid: this?.ref.uuid,
      });
    
      myFeaturer.build();
    
    </script>

I need to pass uuid prop to the <script> tag without define:vars as described here because then my script will be treated as is:inline and I can't import the JavaScript Class MyFeatureHelper, which I need.

How can I get access to uuid and use it like e.g. uuid: this?.ref.uuid, using the data-attribute trick?

How do I get this to work?

1
  • Try: uuid: ref.dataset.uuid. Also I think you have a typo - my-container should be my-feature. Commented Oct 10, 2024 at 14:19

1 Answer 1

0

See Astro docs where there is an example on how to do this with a basic web component.

Alternatively, the following should work:

---
type Props = {
  uuid: string;
};

const { uuid } = Astro.props;
---

<div data-uuid={uuid} id="my-feature"></div>

<script>
  const uuid = document.getElementById('my-feature')?.dataset.uuid
</script>
Sign up to request clarification or add additional context in comments.

15 Comments

thanks but because I add an attribute to the script tag <script data-uuid={uuid}> I cannot import a script import { MyFeatureHelper } from '@/scripts/my-helper'; in between the script tags (see my question). I also get this hint from IDE: This script will be treated as if it has the is:inline` directive because it contains an attribute. Therefore, features that require processing (e.g. using TypeScript or npm packages in the script) are unavailable. See docs for more details: docs.astro.build/en/guides/client-side-scripts/….`?
oh right, I edited my answer.
Ok then I get Property 'uuid' does not exist on type 'DOMStringMap | undefined'.?
That's a TypeScript error warning you of the possibility that the element in question might be undefined. Edited again...
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.