Transfer frontmatter variables to scripts by utilizing data-attributes and apply them within a JavaScript Class

Here is my Astro component that I am working with:

   ---
    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');
    
      myFeature = new MyFeatureHelper(ref as HTMLDivElement, {
        uuid: this?.ref.uuid,
      });
    
      myFeaturer.build();
    
    </script>

I am trying to pass the uuid prop to the <script> tag without using define:vars as mentioned in this post. It's important for me because if I do use define:vars, my script will be treated as is:inline and I can't import the JavaScript Class MyFeatureHelper that I need.

Is there a way for me to access the uuid and utilize it like uuid: this?.ref.uuid, possibly using the data-attribute trick?

Any advice on how to make this setup work correctly would be appreciated!

Answer №1

Check out the Astro documentation for a helpful example of how to accomplish this using a basic web component.

If you prefer, you can also try the following approach:

---
type MyProps = {
  id: string;
};

const { id } = Astro.props;
---

<div data-id={id} id="my-element"></div>

<script>
  const elementId = document.getElementById('my-element')?.dataset.id
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Extract the JSON data and store it in an array

I'm currently working on parsing a JSONObject using JavaScript. My goal is to parse the object from the JSON and assign it to an array. Any suggestions or help would be greatly appreciated. Here's the code I'm working with: Here is my JavaS ...

Using Angular JS, the JSON method is invoked from a location external to the controller

How can I call an inner method from outside a controller in AngularJS? var app; (function (){ app = angular.module("gallery", []); app.controller("galleryController", ['$scope','$http', function($scope, $http){ var gallery = this; ...

What is the best way to manipulate an input field in a controller if the input is not connected to an ng-model?

Received some backend-rendered HTML code. Here is the HTML code: <form name="mk" ng-submit="submit()"> First name:<br> <input type="text" name="firstname" value="Mickey"> <br> Last name:<br> <input ty ...

Having trouble with the req.params command in Express JS when the app is deployed on Heroku?

I have a simple express server code running (provided below). My goal is to access the req.params values through routes. var express = require("express"); var app = express(); var PORT = process.env.PORT || 3000; app.get("/", function(req, res, next){ ...

Testing Angular 2 components with material icons and images

Recently, I finished creating a unique component that showcases an image, material icons, and a custom directive known as ticker. This directive allows for scrolling text if it exceeds the width of the element. https://i.stack.imgur.com/GpDSr.png My next ...

``Changing the value of a class variable in Angular 2 does not result in the

I am facing an issue with a component that contains a variable called myName export class ConversationComponent implements OnInit { private myName: string; showNames(name) { this.myName=name; } } The value is assigned using the showNames() m ...

Encountered an issue with undefined property when attempting to add a second value to an array of

I have been working on the following javascript code: var res = [{}]; for (var idx = 0; idx < json.length; idx++) { // if the environment is already entered in the result if (res[idx].env) { sails.log.debug('Enviro ...

How can we transfer a value from a parent component class to a child subclass?

In my TypeScript file, there are three classes within a single file. I am attempting to transfer a value from the MainComponent class to the TableContent class. I initially tried using super() inside the TableContent class which did not work, and then att ...

Identify the nested Object within the Json data

I am looking to add and name a nested object within my Json data structure. The current structure of my Json is as follows: { "MH": [ { "MHF46": "Ledig", "MHF60": "60", }, ...

Incorporating CCAvenue Payment System with React JS

I am looking to incorporate the CC Avenue Payment gateway into my React JS Application. The goal is that when a user clicks on the Payment button, a CC Avenue payment window should open for them to make the payment. Upon successful completion of the paymen ...

Error in Javascript: DOMException is thrown when the 'cssRules' property cannot be read from 'CSSStyleSheet'. It is not possible to access the rules in this case

I keep encountering the 'DOMException: Failed to read the 'cssRules' property from 'CSSStyleSheet': Cannot access rules'. Can anyone provide suggestions on how to fix this issue? Sample Code function copyStyles(source, target ...

bespoke error notification on the player for a live broadcast

I have a react code snippet below that is responsible for rendering a player. When the condition is true, the ReactJWPlayer code block is executed. const player = ()=> { if(condition) { return ( <ReactJWPlayer ...

Creating unique identifiers for each level within a multidimensional array using JavaScript

I'm currently working on creating a list that contains all the distinct levels within a multidimensional array of objects. Given this dataset... let levels = [ ["P", "B", "L"], ["A", "B", "L3"], ["A", "B", "L3"], ["P", "B", "M"], ["P", "C", ...

Exploring React with Typescript: Examining the attributes of an interface

I am currently developing a node-based editor for neural networks using tensorflow.js to create the networks themselves. TensorFlow.js provides a layers API with various factory functions, each with its own interface for arguments. interface DenseLayerArgs ...

Typescript fails to acknowledge static class methods

I am facing an issue with a typescript function that involves a generic class called "Model" with a static method called "build". Typescript is not recognizing the static methods within the class and displaying errors, although the compiled JavaScript work ...

Modify the appearance of certain text within an input field

I need some help adding style to specific text within an input field. For example, if the user types in "Hello world" and the special text is "world" I want to achieve this result: https://i.sstatic.net/Ozd6n.png This is what my HTML code looks like: & ...

What is the functionality of the large arrow notation when used in conjunction with the value formatter in ag-Grid

In my Angular project, I have created a GridFormatterService service with static methods that can be used for value formatting in ag-Grid. For certain ag-Grids in the project, I need to pass a displayDateAndTime parameter (a boolean flag) from the column ...

Delivering static frontend JavaScript file using ExpressJS

Hey there, I'm running into a bit of trouble when trying to load the frontend JS file on my Express server. Here's how my file structure looks: https://i.sstatic.net/EHDSp.png Here's my Server Code - app.set("view engine", " ...

Restrict allowable dates according to user preference

In my Leave request form, employees can request various types of leaves such as paid leave, unpaid leave, and leave for blood donation. These types are stored in a Mysql table and displayed in a dropdown using the following code: <div class="form-g ...

Raycasting in Three.js is ineffective on an object in motion

Working on a project that combines three.js and typescript, I encountered an issue while attempting to color a sphere by raycasting to it. The problem arises when the object moves - the raycast doesn't seem to acknowledge the new position of the objec ...