#Pass elements of a TypeScript array into <style>

3 messages · Page 1 of 1 (latest)

ivory crow
#

I have an array of elements that could change over time as I update them at the top of my .astro file.

const array = ["a", "b"];
...
---

and in the <style> tag at the bottom of the same file, I want to do something like

{array.map(e => {
  let output = '.' + e + ' {';
  output += 'color: var(--' + e + ')';
  output += '}';
  return output;
})}
<styles>```
so that I get something like
```<style>
.a {
  color: var(--a);
}
.b {
  color: var(--b);
}
</style>```

I want to do this programmatically because, as I mentioned, the content of the array may change and I want all elements in there to be reflected in the `<style>` dynamically.
white rainBOT
#
Still waiting for an answer?

It looks like no-one has responded to your question yet. People might not be available right now or don’t know how to answer your question. Want an answer while you wait? Try asking our experimental bot in #1095492539085230272.

sand kelp
#

You can use the set:html directive, something like this: jsx <style set:html={ array.map(e => { let output = '.' + e + ' {'; output += 'color: var(--' + e + ')'; output += '}'; return output; }).join('') }/> Although, one thing to keep in mind is that this will inline the <style> tag so the styles will not be scoped or bundled

https://docs.astro.build/en/reference/directives-reference/#sethtml