0

So after reading over the docs and then taking a umedy class on Stencil I still cannot seem to get class names to set on my object. for example i have the following

import { Component, h, Prop } from '@stencil/core'

@Component({
tag: 'my-button',
styleUrl: 'my-button.css'
})

export class MyButton {
@Prop() btext: string;
@Prop() btype: string;

render(){
let classNaming: string = '';
switch(this.btype) {
   case "Primary":
       classNaming += 'My-Button-CSS';
       break;
   case "Secondary"
       classNaming += 'My-Button-CSS';
       break;
}

return <button class={classNaming}>this.btext</button>
}
}
}

The issue is the class never shows up on the button. I know in react-bootstrap i saw in a tutorial, but never used react, they have variant="" which is basically what i am wanting to build and having no luck getting this working as Stencil tutorials and advanced items are sparse. The other issue is the classes that are out there are all based on 1.8.

2 Answers2

0

You are forgetting a colon(:) after the second case (case "Secondary"), and there is an extra } at the ending of the document.

You can play around with the code at webcomponents.dev

The final code should be:

import { Component, h, Prop } from "@stencil/core";

@Component({
  tag: "my-button",
  styleUrl: "my-button.css",
})
export class MyButton {
  @Prop() btext: string;
  @Prop() btype: string;

  render() {
    let classNaming: string = "";
    switch (this.btype) {
      case "Primary":
        classNaming += "My-Button-CSS";
        break;
      case "Secondary":
        classNaming += "My-Button-CSS";
        break;
    }

    return <button class={classNaming}>{this.btext}</button>;
  }
}
Puru Vijay
  • 116
  • 1
  • 2
  • I made those changes and it still didn't work when inspecting the code in the browser it never showed up. I did however finally find someone online that was doing kind of what i was getting at and tried it and got it to work. What i ended up doing is below: const classNaming = classname({ 'My-Button-CSS': this.isType1, 'My-Button2-CSS': this.isType2}); – TheWaywardProgrammer Apr 17 '20 at 14:06
0

I think the problem with your code might just be that when the btype prop is not set on your component, then classNaming stays '' (empty string), and then the vdom implementation just leaves the class attribute away when rendering the node because class="" is redundant.

I copied your component into a playground:
https://webcomponents.dev/edit/EVDjWjM0gINeOiJyLl9k?pm=1

It works fine... check index.stories.tsx for how the two different buttons are used. You need to set btype like

<my-button btype="Primary" btext="First Button"></my-button>
Simon Hänisch
  • 4,740
  • 2
  • 30
  • 42