Basics
Create Components​
You can use Component
to create a base class that can be extended into a web
component a.k.a. custom HTML element.
import { Component, prop } from "sinho";
class SimpleGreeting extends Component("simple-greeting", {
name: prop<string>("John"),
}) {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
The class needs to provide a render
method that returns a JSX template.
Since SimpleGreeting
is a custom element it needs to be defined first before
it can be used or constructed. You can use the defineComponents
function to
define it with the tag name given as first argument to Component
:
import { /* … */ defineComponents } from "sinho";
// …
defineComponents(SimpleGreeting);
Optionally, you can provide a prefix:
defineComponents("my-", SimpleGreeting);
You can define multiple components at once:
defineComponents(SimpleGreeting, AnotherComponent);
defineComponents("my-", SimpleGreeting, AnotherComponent);
Usage​
In HTML​
You can specify the component in HTML via its tag name:
<simple-greeting></simple-greeting>
If a prefix (e.g. my-
) was provided, you need to use it:
<my-simple-greeting></my-simple-greeting>
Notice the mandatory closing tag. Custom elements cannot be self-closing.
In JS​
You can construct the component in JavaScript like a normal class:
const greeting = new SimpleGreeting();
greeting.name = "Jane";
document.body.append(greeting);
In JSX​
You can use the component directly in Sinho JSX templates:
<SimpleGreeting name="Jane" />
Shadow DOM​
By default, Sinho renders the template returned by render()
into the
shadow DOM.
This will provide encapsulation and slotting. If this is not desired, you can
disable this by setting the shadow
option on your component to false
:
export class SimpleGreeting extends Component(
"simple-greeting",
{ name: prop<string>("John") },
{ shadow: false },
) {
// …
}
If you disable shadow DOM, the template will be rendered into the light DOM and techniques such as slotting will not work.