6.8 C
New York
Wednesday, February 26, 2025

Plug-and-play net growth with Astro



Astro’s variable scope

While you want front-end interactivity, you possibly can set it up like we’ve completed utilizing a Reactive framework or with vanilla JavaScript. Both manner, Astro works on the server facet. A great way to drive this level house is to take a look at Astro’s assist for variables that may be inserted into the HTML templates. For instance, we may create a beginning worth in index.astro like so:


---
import ReactCounter from '../parts/ReactCounter.jsx';
import SvelteCounter from '../parts/SvelteCounter.svelte';

const startingValue = Math.ground(Math.random() * 100);
---
// …
<h3>That is on the server: {startingValue}</h3>

This shows the random worth generated on the server on the shopper web page. Bear in mind, although, that it’s all completed on the server. If we wished to make use of this worth on the shopper, we may move it into the parts as a parameter. For instance, we may make the Svelte part settle for a parameter like so:


<script>
  export let startingValue;
  let rely = startingValue;

  operate handleClick() {
    rely += 1;
  }
</script>

<div>
  <p>Rely: {rely}</p>
  <button on:click on={handleClick}>Increment</button>
</div>

Discover the export let startingValue syntax, which is Svelte-speak for exposing a pass-in parameter to its guardian. To make use of this again on the index web page you’d sort:



Supply hyperlink

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles