javascriptjsxastrojs

How to modify/change data loaded in the frontmatter in Astro?


I am using Astro to build a basic application where I am loading a JSON Array from a file using import syntax in frontmatter. Now I want to split data in half on every click depending which side of the half you have clicked. I have made a demo in codepen please check.

I just need to understand how do I load a data in frontMatter from API or local file and modify it. I was using script tag to write my methods to do the operations but I cant seem to access the data in script and also I can't access data from script tag into my markup.

---
import Layout from '../layouts/Layout.astro';
import Card from "../components/Card.astro";
import messages from '../content/messages_arr.json'; /* <-- frontmatter */
---

<script>
  export let data_A =  "Data A"
  let data_B =  "Data B"
  
  export let methodA = () =>{ console.log(A)}
  let methodB = () =>{ console.log(B)}
  
</script>

<Layout> /* <-- markup */
<div>
  {message}
  {data_A}
  {data_B}
  <button onclick={methodA}>METHOD A</button>
  <button onclick={methodB}>METHOD B</button>
</div>
</Layout>

Solution

  • Astro components (including their frontmatter code) only run on the server, so you cannot update the GUI in reaction to onClick events or similar. For that, you need client-side JavaScript code, either by using:

    Both are supported by Astro.