Create html elements from tsx syntax using document.createElement
.
- Support for class elements like in React but without lifecycles or rerender
- Support for function elements
- Support for fragments
$ npm install tsx-create-html-element
Update your tsconfig.json:
// tsconfig.json
{
"compilerOptions": {
"jsx": "react",
"jsxFactory": "createElement"
}
}
Jsx code:
import { createElement } from "tsx-create-html-element";
const title = "Hello World";
function sayHi() {
alert(title);
document.getElementById("greet").innerText = title;
}
document.getElementById("app").appendChild(
<div>
<div id="greet" />
<button onclick={sayHi}>Say Hi</button>
</div>
);
Equivalent:
const title = "Hello World";
function sayHi() {
alert(title);
document.getElementById("greet").innerText = title;
}
const divGreetElement = document.createElement("div");
divGreetElement.id = "greet";
const buttonElement = document.createElement("button");
buttonElement.append("SayHi");
const divElement = document.createElement("div");
divElement.append(divGreetElement, buttonElement);
document.getElementById("app").appendChild(divElement);