Skip to content

Instantly share code, notes, and snippets.

@Danetag
Last active May 20, 2020 00:31
Show Gist options
  • Save Danetag/c502042133197ddcc00d601755af3134 to your computer and use it in GitHub Desktop.
Save Danetag/c502042133197ddcc00d601755af3134 to your computer and use it in GitHub Desktop.
import { Component, h, Prop, State, Watch } from '@stencil/core';
const Constants = {
baseClassname: 'my-button',
}
@Component({
tag: 'my-button',
styleUrl: 'button.scss'
})
export class Button {
/**
* Show number of clicks
*/
@Prop({attribute: 'show-click'}) showNbOfClicks: boolean = false;
/**
* Theme
*/
@Prop() theme: "primary" | "secondary" = "primary";
@Watch('theme')
validateTheme(newValue: string) {
const themes = ['primary', 'secondary'];
const themeIsValid = themes.indexOf(newValue) > -1;
if (!themeIsValid) { throw new Error('theme: not a valid theme') }
}
/**
* Number of clicks
*/
@State() numberOfClicks: number = 0;
componentWillLoad() {
this.validateTheme(this.theme);
}
handleClick = () => {
this.nbOfClicks += 1;
}
render() {
const { theme, showNbOfClicks, numberOfClicks } = this;
const classes = [
`${Constant.baseClassname}`,
theme && `${Constant.baseClassname}--${theme}`,
].filter(classname => !!classname).join(' ').trim();
return (
<button class={classes} onClick={this.handleClick}>
<span class="label"><slot /></span>
{ showNbOfClicks && numberOfClicks > 0 && (<span class="nb-of-clicks">{ numberOfClicks }</span>) }
</button>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment