#Transferring data from server side to client side

7 messages · Page 1 of 1 (latest)

dark terrace
#

Within an Astro component, is there a better way to transfer data from server to client than this:

<div data-track-links={trackLinks} class:list={blockClasses}>
  <div data-tracking-level={reel.trackingLevel} class:list={constrainClasses}>
    <slot />
  </div>
</div>

<script>
  const test = document.querySelector('[data-track-links]');
</script>
stoic summitBOT
#

Hi @dark terrace. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Yes, there is a recommended way to transfer data from server to client in Astro components. You can use data-* attributes to store the value of variables in your HTML output. Scripts, including custom elements, can then read these attributes using an element’s dataset property once your HTML loads in the browser.

Here's an example from the Astro documentation (https://docs.astro.build/en/guides/client-side-scripts#pass-frontmatter-variables-to-scripts):

---
const { message = 'Welcome, world!' } = Astro.props;
---

<!-- Store the message prop as a data attribute. -->
<astro-greet data-message={message}>
  <button>Say hi!</button>
</astro-greet>

<script>
  class AstroGreet extends HTMLElement {
    constructor() {
      super();
      // ...
    }
  }
</script>

In this example, a message prop is stored in a data-message attribute, so the custom element can read this.dataset.message and get the value of the prop in the browser.

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

Astro Documentation

How to add client-side interactivity to Astro components using native browser JavaScript APIs.

#

@dark terrace kapa.ai is still learning and improving, please let us how it did by reacting below

dire tiger
dark terrace
dire tiger
#

right, might be because it's then handled differently and attached for every instance.