Frameworkless JSX Runtime
npm install a-jsx-runtimeA JSX runtime which allows using JSX templates to render HTML without the need for any frameworks such as react, preact etc. an allows optimized updates / re-renders by using a Virtual DOM implementation.
* class attribute instead of className
* _ref attribute instead of ref
* _key attribute instead of key
* on-event attribute (e.g. on-click) instead of onEvent
* Suspense: see Suspense section
``TSX
import { render, createRef, rawHtml, Slot, Suspense } from "a-jsx-runtime";
const existingHTMLElement = document.querySelector("#greetings");
const pendingRequest = fetchJSON("/api.json");
const inputRef = createRef
function Card({ bg, children }) {
const style = {
"background-color": bg,
border: "1px solid gray"
};
return (
default content
render( New Products!
<>
Buy Now
inputRef.current!.focus()}>label
{false &&
not gonna render this
}{existingHTMLElement}
// invoke the render call again e.g. when some data has been changed
render(...);
`
For another example see example.tsx.
`sh`
npm install a-jsx-runtime @babel/plugin-transform-react-jsx
* add jsx parser to babel config. e.g
`javascriptimport
// webpack.config.js
module.exports = {
...
module: {
rules: [
...
{
test: /\.tsx$/,
use: [
{
loader: 'babel-loader',
options: {
presets: [
...
],
plugins: [
...
[
"@babel/plugin-transform-react-jsx",
{
"runtime": "automatic", // add the etc automatically.`
"importSource": "a-jsx-runtime", // use jsx functions from the npm module
}
],
]
}
},
],
},
]
},
resolve: {
extensions: ['.ts', '.tsx', '.js', 'jsx', '.json']
},
...
};
* add "jsx": "preserve", to tsconfig.json.
* use vite react plugin
`js
// vite.config.js
import {defineConfig} from 'vite';
import react from '@vitejs/plugin-react';
export default defineConfig(() => ({
plugins: [
react(),
],
// only needed when there is no tsconfig. otherwise the jsxImportSource will automatically be picked up
esbuild: {
jsxImportSource: "a-jsx-runtime",
},
}));
`
* tsconfig
`js
// tsconfig.json
{
"compilerOptions": {
// ...
"moduleResolution": "node16", // is currently needed for typescript to use package exports
"jsx": "preserve",
"jsxImportSource": "a-jsx-runtime",
},
}
When (re-)rendering a list with changing length or order, you can add a _key attribute with the unique identifier to each item, to make sure same rendered DOM Elements are re-used. This helps to maintain external changes (e.g. focus, user input, css animations ...)
example:
`jsx`
<>
{arr
.filter(someDynamicFilter)
.sort(sortFunction)
.map(item => (
))
}
>
After the markup first time is rendered, the reference to the rendered html element will be passed to the _ref attribute.
example:
`tsx
import { createRef } from "./jsx-runtime";
function Comp() {
const ref = createRef
return (
<>
{/ use with createRef /}
{/ use as callback/}
initDatePickerPlugin(el)} />
>
);
}
`
Name of Function Components Slot element which will be replaced by the items having the prop. (see Slot section)
Class name of the html element. Which can be a string or an array for convince.
e.g.
`jsx`
Style attribute for an html element. which can be a string or an object.
example:
`jsx
const style = {
outline: "1px solid gray",
"padding-top": "10px",
background: isActive && "red", // falsy values won't be rendered
}
Exports
$3
render(markup , root, append?): void;| Param | Type | Default | Description |
| --- | --- | --- | --- |
| markup |
JSX \| string \| number \| null \| boolean \| undefined \| HTMLElement | | to be rendered content |
| root | HTMLElement | | container for the content to be rendered into |
| [append] | boolean | false | should the provided markup be appended to the existing content, or replace root's child elements |Renders the provided jsx as markup inside the
root html element.`jsx
import { render } from "a-jsx-runtime";render(
{value}, document.querySelector("#root"))
`$3
Creates a function which can be passed as the value for the
_ref prop and later the rendered HTML Element be accessed via the .current property on it:`tsx
import { createRef } from "./jsx-runtime";function Comp() {
const ref = createRef();
return (
<>
ref.current.focus() } />
>
);
}
`$3
The provided string will be rendered as markup and not escaped / sanitized.
Use this with caution because theoretically it allows broken html or even xss attacks
`tsx
import { rawHtml } from "a-jsx-runtime";const richText = await fetchCitation();
render(
{ rawHtml(richText) } ,
el
);
`$3
Slots are named containers which are placeholders inside a function component and will be replaced by the content passed by the components consumer.
| Param | Type | Description |
| --- | --- | --- |
| name |
string | name to identify this slot when content is passed |
| hostsChildren | JSXChild | props.children from the parent component functions which contains the slotable elements |
| [fallbackContent] | JSXChild | fallback markup which will be rendered incase the component is used with out content having the _slot prop for this slot |example
`jsx
function Dialog({children}) {
return (
fallback text
);
}render (
,
element
)
`$3
Component to render placeholder markup till some promise is resolved and the markup is updated
| Param | Type | Description |
| --- | --- | --- |
| placeholder |
JSXChild | markup to be rendered during the time promise hasn't been resolved |
| promise | Promise | promise which needs to be resolved for the actual markup to be rendered |
| template | function | function which will be called with promises resolve value and should return the desired jsx markup |example:
`jsx
import { Suspense } from "a-jsx-runtime"; placeholder={ }
promise={pendingRequest}
template={(response) =>
}
/>
`$3
Renders the provided text as html comments in the generated html.
`jsx
import { HTMLComment } from "a-jsx-runtime";
{/ @TODO: move to dedicated template /}
`will render
`html
`$3
JSX Fragments allows sibling elements to be rendered without the need of a parent element.
You usually don't have to explicitly import it, simply use
`jsx
<>
1
2
>
`and JSX transformer will replace it with Fragments.
But in case you want to pass some props, then you need to use it as:
`jsx
import { Fragment } from "a-jsx-runtime";
1
2
`$3
Basic type for props object that Function Components can receive:
`tsx
import { JsxProps } from "a-jsx-runtime";function Dialog({ open = false, children }: JsxProps) {}
`But it is always better if you define the prop type of the component explicitly, to allow type checking for the props when this component is used in other places.
Demo
Checkout repo and
npm start` to see the demo in the example folder in action.Github: @mbehzad