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.
The only styling variables you will be able to read at runtime are CSS custom properties.
CSS/SCSS :
:root {
--foo-bar: red;
}
JS/TS :
var bodyStyles = window.getComputedStyle(document.body);
var fooBar = bodyStyles.getPropertyValue('--foo-bar'); //get red
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:
.element {
background-color: var(--color);
}
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:
import { Component, State, Host } from '@stencil/core';
export class MyComponent {
@State() color = 'red';
render() {
return (
<Host style={{'--color': this.color}}>
<div>Hello, World!</div>
</Host>
);
}
}
Note:
color
with @State()
to make the value reactive (i.e. the render()
function is called whenever the value of color
changes).<Host>
functional component to set a property on the host element (in this case <my-component>
).