Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/lullaby6/custom-html-element

NPM Package - Create reusable and reactive Web Components using Custom Element API
https://github.com/lullaby6/custom-html-element

custom-element custom-elements javascript js npm npm-package web-component web-components

Last synced: 22 days ago
JSON representation

NPM Package - Create reusable and reactive Web Components using Custom Element API

Awesome Lists containing this project

README

        

# custom-html-element

Create reusable and reactive Web Components using Custom Element API.

# Installation

Using NPM:

```sh
npm install custom-html-element
```

Using the CDN:

```html

```

# Usage

## Sintax showcase

JavaScript:

```js
// if you are using the CDN, you don't need import anything
import {customHTMLElement} from 'custom-html-element'

function MyElement(){
return `

Hello World


`
}

// use the customHTMLElement method to define the custom element
customHTMLElement(MyElement)
```

HTML:

```html

```

## Using children elements

the inner HTML of the element ```slot``` inside of your custom element will be setted by the original inner HTML of the custom element.

JavaScript:

```js
function MyElement({count}){
return `

World



`
}
```

HTML:

```html

World

```

## Let's create a simple button counter

JavaScript:

```js
import {customHTMLElement, HTMLElementAddEventListener} from 'custom-html-element'

function MyCounter({count}){

// creating a reference to hit the button
const ref = crypto.randomUUID()

/*
use the HTMLElementAddEventListener method for add a
event listener to elements inside custom elements
*/
HTMLElementAddEventListener(ref, 'click', () => {

// when any attribute of the custom element is updated, it will be re-rendered
this.setAttribute('count', parseInt(count) + 1)

})

return `
${count}
`
}

customHTMLElement(MyCounter)
```

HTML:

```html

```

## Now let's create a simple ToDo List App

JavaScript:

```js
import {createHTMLElement, HTMLElementAddEventListener} from './index.js'

function TodoList({todos}) {
todos = JSON.parse(todos)

const formRef = crypto.randomUUID()

HTMLElementAddEventListener(formRef, 'submit', (event) => {
event.preventDefault()
const formData = new FormData(event.target)
const formProps = Object.fromEntries(formData)

todos.push({id: crypto.randomUUID(), text: formProps['todo']})

this.setAttribute('todos', JSON.stringify(todos))
})

todos.forEach(todo => {
HTMLElementAddEventListener(todo.id, 'click', (event) => {
todos.splice(todos.findIndex(todo => todo.id === event.target.id), 1)

this.setAttribute('todos', JSON.stringify(todos))
})
})

return `







    ${todos.map(todo => `
  • ${todo.text}
  • `
    ).join('')}


`
}

createHTMLElement(TodoList)
```

HTML:

```html

```