I need to make a custom component in stencil where the color is dynamic.
Any way to take the value of variable from tsx and access it on scss file.
The code is below.
I need to make a custom component in stencil where the color is dynamic.
Any way to take the value of variable from tsx and access it on scss file.
The code is below.
2
Answers
The only styling variables you will be able to read at runtime are CSS custom properties.
CSS/SCSS :
JS/TS :
As @matthieu-riegler noted you’re looking for CSS custom properties. If you only ever need the value in CSS one way would be to ask the users of the component to set the color directly with a custom property on the element (e.g.
<my-component style="--color: #003366"></my-component>
). Then you could use it in your CSS:If you also need the value in JS (or find setting a attribute/property on the element better, for whatever reason), then instead of defining the color in the CSS and reading from JS, you could also go the other way around:
Note:
color
with@State()
to make the value reactive (i.e. therender()
function is called whenever the value ofcolor
changes).<Host>
functional component to set a property on the host element (in this case<my-component>
).