#frontmatter api string to client side script

3 messages · Page 1 of 1 (latest)

silent needle
#

I've read your docs but it's still unclear to me - how can i send the client side script a string via the frontmatter?
I hope you can give me a very very simple example or two.

iron dewBOT
#

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

#

You can pass a string from the frontmatter to a client-side script using data-* attributes. Here's a simple example:

  1. Create an Astro component with a frontmatter variable and store it in a data-* attribute:
---
const message = 'Hello, world!';
---

<div data-message={message}>
  <button>Click me!</button>
</div>

<script>
  class MyComponent extends HTMLElement {
    constructor() {
      super();
      // Read the message from the data attribute.
      const message = this.dataset.message;
      const button = this.querySelector('button');
      button.addEventListener('click', () => {
        alert(message);
      });
    }
  }

  customElements.define('my-component', MyComponent);
</script>
  1. Use the component in another Astro file:
---
import MyComponent from '../components/MyComponent.astro';
---

<my-component></my-component>

In this example, the message variable is stored in a data-message attribute. The custom element reads the data-message attribute using this.dataset.message and displays it in an alert when the button is clicked.

Source: 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:

Astro Documentation

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