This is a lightweight JavaScript library, that allows you to dynamically create reuseable Components through HTML Tags. You will use plain and standard HTML with custom elements. However the library only comes with 2 built-in Component, so there is no bloat, no new HTML dialect, no boilerplate, no syntax sugar to learn.
Add the following script tag as the first script of your html document.
<script src="https://YanSchw.github.io/tiny-components/tiny-components.js"></script>
A Component is just a HTML Tag and an anonymous Create-Function (see below). This function takes in:
- A node this is the Node | Element in the DOM. It is the same object you retrieve e.g. through document.querySelector(...);
- A state this is tiny-components State of this DOM object. You can use it to do common operations on your element.
First, define your Component in JavaScript.
component('my-hello-world-component', (node, state) => {
node.innerHTML = state.sometextvalue;
});
Then, add an HTML Tag that has the same name as your Component into the DOM.
<my-hello-world-component sometextvalue="Hello!"></my-hello-world-component>
Attributes you define in the HTML are available as Attributes in the JavaScript state.
'Hello!' now appears in the Component's place.
If you want to redraw a Component, you have to explicitly tell the library to do so.
component('my-redrawing-button', (node, state) => {
let button = document.createElement('button');
button.innerHTML = 'Redraw this Component';
button.onclick = () => {
state.redraw();
};
node.appendChild(button);
});
Using these functions your can spare some typing:
function select(cssSelector) {
return document.querySelector(cssSelector);
}
function selectAll(cssSelector) {
return document.querySelectorAll(cssSelector);
}
Using this function
function createNode(tag, parent, lambda) {
let element = document.createElement(tag);
lambda(element);
parent.appendChild(element);
}
you can easily create new DOM Elementes as one-liners or nest them within each other. For example:
createNode('div', select('body'), div => {
createNode('p', div, p => p.innerText = 'Hello!');
});
creates a 'Hello!' Paragraph within a div within the HTML body.
The built-in include Component is a C-like cut-and-paste tool, that let's you inject HTML-Text.
<include value="/html/navigation.html"></include>
The built-in echo Component Parses a block of JavaScript and puts the last evaluated expression into the innerHTML.
<echo>
let a = "<p>he";
let b = "llo</p>";
a + b;
</echo>
This creates a Paragraph, that says hello
Here are some examples: