An open API service indexing awesome lists of open source software.

https://github.com/saber2pr/jsx

write jsx in your html.only 1kb dep.
https://github.com/saber2pr/jsx

jsx

Last synced: 3 months ago
JSON representation

write jsx in your html.only 1kb dep.

Awesome Lists containing this project

README

        

### jsx

write jsx in your html. only 1kb dep.

```js
// it returns a dom object.
const app = jsx`

Hello World!
` //
Hello World!

document.body.append(app) // append it.
```

it's the same as:

```js
const app = document.createElement("div")
app.innerHTML = "Hello World!"
document.body.append(app)
```

or use `jsx.render`:

```js
jsx.render(app, document.body)
```

### Start

add it to the head. have a try!

```html

```

---

### Example

[demo](https://saber2pr.top/jsx/example)

```html








// functional component
const List = ({ list }) =>
list.map(n => jsx`<li style=${{ color: "red" }}>${n}</li>`)

// <ul />
const Ul = jsx`<ul><${List} list=${[1, 2, 3]} /></ul>`

// append to dom.
document.getElementById("root").append(Ul)

```

#### 1. Ref

```js
const ref = {} // must be an object
const button = jsx`
console.log(ref.current)}>add`

// functional ref handle
const button = jsx` (ref.current = btn)} onClick=${() =>
console.log(ref.current)}>add`
```

> the ref could be passed from functional component to the functional component, no need forwardRef.(different from react)

#### 2. Fragment

```js
const paras = jsx`
<${jsx.frag}>

1


2


3


${jsx.frag}>` // #document-fragment

document.getElementById("root").append(paras)
```

#### 3. Lazy

```js
const fetchData = value =>
new Promise(resolve => setTimeout(resolve, 1000, value))

const App = async ({ value }) => {
const data = await fetchData(value)
return jsx`

${data}

`
}

const Index = jsx`
<${jsx.Suspense} fallback=${jsx`

loading...

`}>
<${App} value=${"qwq"}/>
${jsx.Suspense}>`

document.getElementById("root").append(Index)
```

or import()

```js
const App = jsx.lazy(import("./app.js"))

// or return a default prop: () => Promise<{default: HTMLElement}>
const App = jsx.lazy(async ({ value }) => {
const data = await fetchData(value)
return {
default: jsx`

${data}

`
}
})
```

#### 4. createElement

```js
jsx.createElement(`div`, { id: "hello" }, "Hello World!") //

Hello World!

const fontSize = 2
jsx.createElement(`h${fontSize}`, {}, "Hello World!") //

Hello World!


```

### Reference

[htm](https://github.com/developit/htm)

> Author: saber2pr