Use TSX to create HTML elements within your typscript code
Here in very short words how you can use TSX to create HTML elements inside typescript code in HTML syntax.
Edit tsconfig.json
"jsx": "react",
"jsxFactory": "createElement",
"jsxFragmentFactory": "Fragment",
Create jsx.d.ts
declare namespace JSX {
interface IntrinsicElements {
[elemName: string]: any; //-- allow all elements
}
}
Create or rename index.tsx
Create the JSX factory function:
//-- createElement function for TSX
function createElement<K extends keyof HTMLElementTagNameMap>(
tag: K | ((props: any) => HTMLElement),
props: Partial<HTMLElementTagNameMap[K]> | null,
...children: (HTMLElement | string)[]
): HTMLElement {
//-- if tag is a function (for components)
if (typeof tag === "function") {
return tag({ ...props, children });
}
//-- create element
const element = document.createElement(tag);
//-- set attributes
if (props) {
for (const [key, value] of Object.entries(props)) {
if (key in element) {
(element as any)[key] = value;
} else {
element.setAttribute(key, String(value));
}
}
}
//-- add children
children.forEach(child => {
if (typeof child === "string") {
element.appendChild(document.createTextNode(child));
} else {
element.appendChild(child);
}
});
return element;
}
Now you can create HTML elements within you code like so:
const myElement: HTMLElement = (
<div>Hello World!</div>
);
document.body.appendChild(myElement);