本文へ移動

JSX ​

hono/jsx を使うと、JSX 構文で HTML を記述できます。

hono/jsx はクライアント側でも動作しますが、多くの場合はサーバー側でコンテンツをレンダリングする際に使います。ここでは、サーバーとクライアントに共通する JSX の機能を紹介します。

設定 ​

JSX を使うには、tsconfig.json を変更します。

tsconfig.json:

json
{
  "compilerOptions": {
    "jsx": "react-jsx",
    "jsxImportSource": "hono/jsx"
  }
}

pragma ディレクティブを使うこともできます。

ts
/** @jsx jsx */
/** @jsxImportSource hono/jsx */

Deno の場合は、tsconfig.json ではなく deno.json を変更します。

json
{
  "compilerOptions": {
    "jsx": "precompile",
    "jsxImportSource": "@hono/hono/jsx"
  }
}

使い方 ​

情報

クイックスタートからそのまま進めている場合、メインファイルの拡張子は .ts です。.tsx に変更しないと、アプリケーションを実行できません。この変更に合わせて package.json(Deno の場合は deno.json)も修正してください。たとえば、開発スクリプトの bun run --hot src/index.ts は bun run --hot src/index.tsx に変更します。

index.tsx:

tsx
import { Hono } from 'hono'
import type { FC } from 'hono/jsx'

const app = new Hono()

const Layout: FC = (props) => {
  return (
    <html>
      <body>{props.children}</body>
    </html>
  )
}

const Top: FC<{ messages: string[] }> = (props: {
  messages: string[]
}) => {
  return (
    <Layout>
      <h1>Hello Hono!</h1>
      <ul>
        {props.messages.map((message) => {
          return <li>{message}!!</li>
        })}
      </ul>
    </Layout>
  )
}

app.get('/', (c) => {
  const messages = ['Good Morning', 'Good Evening', 'Good Night']
  return c.html(<Top messages={messages} />)
})

export default app

メタデータのホイスティング ​

コンポーネント内に <title>、<link>、<meta> などの文書メタデータタグを直接記述できます。これらのタグは、自動的に文書の <head> に移動されます。適切なメタデータを決めるコンポーネントから離れた場所で <head> がレンダリングされる場合に、特に便利です。

tsx
import { Hono } from 'hono'

const app = new Hono()

app.use('*', async (c, next) => {
  c.setRenderer((content) => {
    return c.html(
      <html>
        <head></head>
        <body>{content}</body>
      </html>
    )
  })
  await next()
})

app.get('/about', (c) => {
  return c.render(
    <>
      <title>About Page</title>
      <meta name='description' content='This is the about page.' />
      about page content
    </>
  )
})

export default app

情報

ホイスティングしても既存の要素は削除されません。後に現れる要素が末尾に追加されます。たとえば、<head> に <title>Default</title> があり、コンポーネントが <title>Page Title</title> をレンダリングすると、両方のタイトルが head に含まれます。

Fragment ​

Fragment を使うと、余分なノードを追加せずに複数の要素をまとめられます。

tsx
import { Fragment } from 'hono/jsx'

const List = () => (
  <Fragment>
    <p>first child</p>
    <p>second child</p>
    <p>third child</p>
  </Fragment>
)

正しく設定されていれば、<></> と記述することもできます。

tsx
const List = () => (
  <>
    <p>first child</p>
    <p>second child</p>
    <p>third child</p>
  </>
)

PropsWithChildren ​

PropsWithChildren を使うと、関数コンポーネントの子要素を正しく型推論できます。

tsx
import { PropsWithChildren } from 'hono/jsx'

type Post = {
  id: number
  title: string
}

function Component({ title, children }: PropsWithChildren<Post>) {
  return (
    <div>
      <h1>{title}</h1>
      {children}
    </div>
  )
}

生の HTML の挿入 ​

HTML を直接挿入するには、dangerouslySetInnerHTML を使います。

tsx
app.get('/foo', (c) => {
  const inner = { __html: 'JSX &middot; SSR' }
  const Div = <div dangerouslySetInnerHTML={inner} />
})

メモ化 ​

memo で計算済みの文字列をメモ化し、コンポーネントを最適化します。

tsx
import { memo } from 'hono/jsx'

const Header = memo(() => <header>Welcome to Hono</header>)
const Footer = memo(() => <footer>Powered by Hono</footer>)
const Layout = (
  <div>
    <Header />
    <p>Hono is cool!</p>
    <Footer />
  </div>
)

コンテキスト ​

useContext を使うと、props を経由して値を渡さずに、コンポーネントツリーのどの階層でもデータをグローバルに共有できます。

tsx
import type { FC } from 'hono/jsx'
import { createContext, useContext } from 'hono/jsx'

const themes = {
  light: {
    color: '#000000',
    background: '#eeeeee',
  },
  dark: {
    color: '#ffffff',
    background: '#222222',
  },
}

const ThemeContext = createContext(themes.light)

const Button: FC = () => {
  const theme = useContext(ThemeContext)
  return <button style={theme}>Push!</button>
}

const Toolbar: FC = () => {
  return (
    <div>
      <Button />
    </div>
  )
}

// ...

app.get('/', (c) => {
  return c.html(
    <div>
      <ThemeContext.Provider value={themes.dark}>
        <Toolbar />
      </ThemeContext.Provider>
    </div>
  )
})

非同期コンポーネント ​

hono/jsx は非同期コンポーネントをサポートしており、コンポーネント内で async/await を使えます。 c.html() でレンダリングすると、自動的に完了を待機します。

tsx
const AsyncComponent = async () => {
  await new Promise((r) => setTimeout(r, 1000)) // sleep 1s
  return <div>Done!</div>
}

app.get('/', (c) => {
  return c.html(
    <html>
      <body>
        <AsyncComponent />
      </body>
    </html>
  )
})

Suspense Experimental ​

React のような Suspense 機能を利用できます。 非同期コンポーネントを Suspense でラップすると、最初に fallback の内容がレンダリングされます。Promise が解決されると、待機していたコンテンツが表示されます。 renderToReadableStream() と組み合わせて使えます。

tsx
import { renderToReadableStream, Suspense } from 'hono/jsx/streaming'

//...

app.get('/', (c) => {
  const stream = renderToReadableStream(
    <html>
      <body>
        <Suspense fallback={<div>loading...</div>}>
          <Component />
        </Suspense>
      </body>
    </html>
  )
  return c.body(stream, {
    headers: {
      'Content-Type': 'text/html; charset=UTF-8',
      'Transfer-Encoding': 'chunked',
    },
  })
})

ErrorBoundary Experimental ​

ErrorBoundary を使うと、子コンポーネントのエラーを捕捉できます。

次の例では、エラーが発生すると fallback に指定した内容が表示されます。

tsx
function SyncComponent() {
  throw new Error('Error')
  return <div>Hello</div>
}

app.get('/sync', async (c) => {
  return c.html(
    <html>
      <body>
        <ErrorBoundary fallback={<div>Out of Service</div>}>
          <SyncComponent />
        </ErrorBoundary>
      </body>
    </html>
  )
})

ErrorBoundary は非同期コンポーネントや Suspense と組み合わせることもできます。

tsx
async function AsyncComponent() {
  await new Promise((resolve) => setTimeout(resolve, 2000))
  throw new Error('Error')
  return <div>Hello</div>
}

app.get('/with-suspense', async (c) => {
  return c.html(
    <html>
      <body>
        <ErrorBoundary fallback={<div>Out of Service</div>}>
          <Suspense fallback={<div>Loading...</div>}>
            <AsyncComponent />
          </Suspense>
        </ErrorBoundary>
      </body>
    </html>
  )
})

StreamingContext Experimental ​

StreamingContext を使うと、Suspense や ErrorBoundary などのストリーミングコンポーネントを設定できます。コンテンツセキュリティポリシー(CSP)のために、これらのコンポーネントが生成する script タグに nonce 値を追加する際に便利です。

tsx
import { Suspense, StreamingContext } from 'hono/jsx/streaming'

// ...

app.get('/', (c) => {
  const stream = renderToReadableStream(
    <html>
      <body>
        <StreamingContext
          value={{ scriptNonce: 'random-nonce-value' }}
        >
          <Suspense fallback={<div>Loading...</div>}>
            <AsyncComponent />
          </Suspense>
        </StreamingContext>
      </body>
    </html>
  )

  return c.body(stream, {
    headers: {
      'Content-Type': 'text/html; charset=UTF-8',
      'Transfer-Encoding': 'chunked',
      'Content-Security-Policy':
        "script-src 'nonce-random-nonce-value'",
    },
  })
})

scriptNonce の値は、Suspense と ErrorBoundary コンポーネントが生成するすべての <script> タグに自動的に追加されます。

html ミドルウェアとの連携 ​

JSX と HTML のミドルウェアを組み合わせると、強力なテンプレート機能を実現できます。 詳しくは、HTML ミドルウェアのドキュメントを参照してください。

tsx
import { Hono } from 'hono'
import { html } from 'hono/html'

const app = new Hono()

interface SiteData {
  title: string
  children?: any
}

const Layout = (props: SiteData) =>
  html`<!doctype html>
    <html>
      <head>
        <title>${props.title}</title>
      </head>
      <body>
        ${props.children}
      </body>
    </html>`

const Content = (props: { siteData: SiteData; name: string }) => (
  <Layout {...props.siteData}>
    <h1>Hello {props.name}</h1>
  </Layout>
)

app.get('/:name', (c) => {
  const { name } = c.req.param()
  const props = {
    name: name,
    siteData: {
      title: 'JSX with html sample',
    },
  }
  return c.html(<Content {...props} />)
})

export default app

JSX レンダラーミドルウェアとの併用 ​

JSX レンダラーミドルウェアを使うと、JSX で HTML ページをより簡単に作成できます。

型定義の上書き ​

型定義を上書きして、独自の要素や属性を追加できます。

ts
declare module 'hono/jsx' {
  namespace JSX {
    interface IntrinsicElements {
      'my-custom-element': HTMLAttributes & {
        'x-event'?: 'click' | 'scroll'
      }
    }
  }
}

MIT ライセンスで公開されています。