skip to Main Content

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.

https://stackblitz.com/edit/stenicil-starter-component-oeyzhz?file=src%2Fcomponents%2Fmy-component%2Fmy-component.tsx&file=src%2Fcomponents%2Fmy-component%2Fmy-component.css

enter image description here

2

Answers


  1. 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
    
    Login or Signup to reply.
  2. 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:

    1. I decorated color with @State() to make the value reactive (i.e. the render() function is called whenever the value of color changes).
    2. I used the <Host> functional component to set a property on the host element (in this case <my-component>).
    3. I defined a CSS custom property on that host element. Instead you could also apply it on a child element.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search