Bob Ramsey
Bob Ramsey

Reputation: 617

using variables and/or async variables in stenciljs @component decorator

I'm not even sure if this is technically possible, let alone advisable, but thought I'd ask.

Is it possible to use variables or the result of functions in a stenciljs @Component decorator?

What I'm trying to do is use fetch to get a stylesheet from a cdn and then apply it to my component. I know there are a couple of different ways to do this and just started wondering if this was even possible. My guess is that it is not. I'm thinking something like:

@Component( {
  tag: 'my-component',
  styles: await getMyStylesheet(),
  shadow: true
} )

where getMyStylesheet() is a function like:

public async getMyStylesheet(): Response<string> {
  const r = await fetch('https://my.cdn/file.css');
  const data = await r.text();
  return Promise.resolve(data ?? '');
}

Not even sure where that function would live. Not w/in my component's class or before the decorator. Maybe in another file and imported????

As it is, I just use

@State() myCSS = '';
async componentWillLoad(): Promise<boolean> {
  const r = await fetch('https://my.cdn/file.css');
  const data = await r.text();
  this.myCSS = data ?? '';
  return Promise.resolve(true);
}

render() {
  return (
    <style>{this.myCSS}</style>
  )
}

And that seems to work fine. But I got curious and thought someone might know for sure.

Upvotes: 0

Views: 67

Answers (1)

TemidoRocha
TemidoRocha

Reputation: 66

I think the best approach would be to import your stylesheet from your index.html:

<head>
      <title>Your App</title>
      <link rel="stylesheet" href="https://my.cdn/file.css" />
</head>

In case you want it specific to your component or you don't have access to the root html you can add it this way in your render function:

render() {
    return (
        <div>
            <link rel="stylesheet" href="https://my.cdn/file.css" />
        <p>Your component content goes here</p>
        </div>
    );
}

Upvotes: 0

Related Questions