Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StencilJS | Apply host styles to component

I am trying to apply the styles from the website where a stencilJS component is included ... but don't know how.

import { Component } from '@stencil/core';

@Component({
  tag: 'menu-component',
  styleUrl: 'menu-component.css',
  shadow: true
})

export class MyComponent {

 render() {
    return (
      <div>
        <h1>Hello World</h1>
        <p id="red">This is JSX!</p>
      </div>
    );
  }
}

The component is included like this:

<link rel="stylesheet" href="css/main.css" type="text/css" />
<script src='https://unpkg.com/[email protected]/dist/mycomponent.js'></script>
<my-component></my-component>

In my main.css file I have something like this:

#red{
    color: red;
}

I would like the style to be applied to the element from the stencil component. Is this possible?

like image 557
Ciprian Avatar asked Jan 18 '19 13:01

Ciprian


People also ask

What is Host in Stenciljs?

<Host> is a virtual component, a virtual API exposed by stencil to declaratively set the attributes of the host element, it will never be rendered in the DOM, i.e. you will never see <Host> in Chrome Dev Tools for instance.

How do you create a component stencil?

Stencil components are created by adding a new file with a . tsx extension, such as my-first-component. tsx , and placing them in the src/components directory.

What is Host element?

To turn an Angular component into something rendered in the DOM you have to associate an Angular component with a DOM element. We call such elements host elements. A component can interact with its host DOM element in the following ways: It can listen to its events.

Does Stenciljs react?

Stencil is a React-inspired web component library. It is using the same JSX as React and some of the same concepts (Render function, props, state). However, Stencil differs as it compiles to an optimal bundle, creating Virtual DOM that is consolidated directly into the DOM itself (no VDOM to VDOM comparison).


1 Answers

You can use css variables for this. Look at the following code samples:

index.html

<my-component style="--text-color:red;"></my-component>

my-component.css

#red {
    color: var(--text-color, black);
}

In the component's styling you assign a CSS variable as value to the text color of the class [id="red"]. In your application, you're now able to change the color by setting the value of the variable.

like image 118
StefanN Avatar answered Oct 18 '22 00:10

StefanN