In my Astro app I need to pass a variable from the server (frontmatter) to the client.
Like the documentation describe there are two options.
- use data-attribute
- use
defineVars
As far as I can see now, I can't use both of them?
I need
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');
const uuid = ref?.dataset.uuid;
console.log(uuid);
myFeature = new MyFeatureHelper(ref as HTMLDivElement, {
uuid: uuid,
});
myFeaturer.build();
</script>
Above is working fine, it's passing correct the variable uuid from the server to the client.
I need a dynamic data-attribute id like:
---
const randomId = Math.random().toString(36).slice(2, 11);
---
<div class="my-feature" data-uuid={uuid} id="my-feature" data-id={randomId}></div>
I need the ref: const ref = document.getElementById('my-feature'); to pass the variables from server to client. So how do I pass data-id attribute and its value now?
I can't use Astro defineVars here, because in that script tag I am also importing a module (import { MyFeatureHelper } from '@/scripts/my-helper';).
Is there a solution for this?
data-idin the exact same way, as you are doing fordata-uuid...?randomIdto pass to the<script>tag (from server to client) and use it there preferably like:const ref = document.querySelector(`[data-id="${randomId}"]`);ref(for something else) like:const ref = document.getElementById('my-feature');. But this ref should be unique likeref.currentin React. So I thought I can do something like:const ref = document.getElementById(my-feature-${randomId});. But that doesn't work because first I have to get the variablerandomId. To getrandomId, I need it from a data-attribute likeconst randomId = ref?.dataset.randomId;, but then I can't get element by id because I need the ref for that?data-uuidof the "corresponding" div element, that came before the script? Then you should probably rather make use ofdocument.currentScriptto get the reference to the current script element, and then navigate the DOM from there, to find the preceding div element ...?