@neumatter/webc
v1.1.1
Published
Module to extend and use web components.
Downloads
11
Maintainers
Readme
A module for creating Web Components.
Install
npm i @neumatter/webc
Getting Started
import * as webC from '@neumatter/webc'
class ThemeButton extends webC.WebComponent {
constructor () {
// always call super first
super()
const theme = localStorage.getItem('data-theme')
const { matches: prefersDark } = matchMedia('(prefers-color-scheme: dark)')
// the context that will be used to alter element
this.context.dark = 'bi-sun-fill'
this.context.light = 'bi-moon-fill'
// set the theme state if found in storage or prefersDarkMode
this.state.theme = theme ? theme : prefersDark ? 'dark' : 'light'
// use the state.theme as the key to get context and set state.themeClass
this.state.themeClass = this.context[this.state.theme]
}
// render will be called on load and state changes
// renders the doc
render () {
const root = document.documentElement
const { theme } = this.state
root.setAttribute('data-theme', theme)
localStorage.setItem('data-theme', theme)
return `
<i id="btni" class="bi ${this.state.themeClass}"></i>
`
}
// on['Event'] - adds eventListener
onClick = () => {
// change the theme
const theme = this.state.theme === 'dark' ? 'light' : 'dark'
// setState
this.setState({
theme,
themeClass: this.getContext(theme)
})
}
}
webC.define('theme-button', ThemeButton)