コンテンツにスキップ

JSX レンダラーミドルウェア

JSX レンダラーミドルウェアを使用すると、`c.setRenderer()` を使用せずに、`c.render()` 関数で JSX をレンダリングする際のレイアウトを設定できます。さらに、`useRequestContext()` を使用することで、コンポーネント内で Context のインスタンスにアクセスできます。

インポート

TypeScript
import { Hono } from 'hono'
import { jsxRenderer, useRequestContext } from 'hono/jsx-renderer'

使用方法

JSX
const app = new Hono()

app.get(
  '/page/*',
  jsxRenderer(({ children }) => {
    return (
      <html>
        <body>
          <header>Menu</header>
          <div>{children}</div>
        </body>
      </html>
    )
  })
)

app.get('/page/about', (c) => {
  return c.render(<h1>About me!</h1>)
})

オプション

オプション docType: boolean | string

HTMLの先頭にDOCTYPEを追加したくない場合は、`docType`オプションを`false`に設定します。

TSX
app.use(
  '*',
  jsxRenderer(
    ({ children }) => {
      return (
        <html>
          <body>{children}</body>
        </html>
      )
    },
    { docType: false }
  )
)

DOCTYPEを指定することもできます。

TSX
app.use(
  '*',
  jsxRenderer(
    ({ children }) => {
      return (
        <html>
          <body>{children}</body>
        </html>
      )
    },
    {
      docType:
        '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">',
    }
  )
)

オプション stream: boolean | Record<string, string>

`true` に設定するか、Record 値を提供すると、ストリーミングレスポンスとしてレンダリングされます。

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

app.get(
  '*',
  jsxRenderer(
    ({ children }) => {
      return (
        <html>
          <body>
            <h1>SSR Streaming</h1>
            {children}
          </body>
        </html>
      )
    },
    { stream: true }
  )
)

app.get('/', (c) => {
  return c.render(
    <Suspense fallback={<div>loading...</div>}>
      <AsyncComponent />
    </Suspense>
  )
})

`true` が設定されている場合、次のヘッダーが追加されます

TypeScript
{
  'Transfer-Encoding': 'chunked',
  'Content-Type': 'text/html; charset=UTF-8',
  'Content-Encoding': 'Identity'
}

Record 値を指定することで、ヘッダー値をカスタマイズできます。

ネストされたレイアウト

`Layout` コンポーネントを使用すると、レイアウトをネストできます。

TSX
app.use(
  jsxRenderer(({ children }) => {
    return (
      <html>
        <body>{children}</body>
      </html>
    )
  })
)

const blog = new Hono()
blog.use(
  jsxRenderer(({ children, Layout }) => {
    return (
      <Layout>
        <nav>Blog Menu</nav>
        <div>{children}</div>
      </Layout>
    )
  })
)

app.route('/blog', blog)

`useRequestContext()`

`useRequestContext()` は Context のインスタンスを返します。

TSX
import { useRequestContext, jsxRenderer } from 'hono/jsx-renderer'

const app = new Hono()
app.use(jsxRenderer())

const RequestUrlBadge: FC = () => {
  const c = useRequestContext()
  return <b>{c.req.url}</b>
}

app.get('/page/info', (c) => {
  return c.render(
    <div>
      You are accessing: <RequestUrlBadge />
    </div>
  )
})

警告

Deno の `precompile` JSX オプションでは `useRequestContext()` を使用できません。`react-jsx` を使用してください。

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

`ContextRenderer` の拡張

以下のように `ContextRenderer` を定義することで、レンダラーに追加のコンテンツを渡すことができます。これは、たとえば、ページに応じて head タグの内容を変更したい場合に便利です。

TSX
declare module 'hono' {
  interface ContextRenderer {
    (
      content: string | Promise<string>,
      props: { title: string }
    ): Response
  }
}

const app = new Hono()

app.get(
  '/page/*',
  jsxRenderer(({ children, title }) => {
    return (
      <html>
        <head>
          <title>{title}</title>
        </head>
        <body>
          <header>Menu</header>
          <div>{children}</div>
        </body>
      </html>
    )
  })
)

app.get('/page/favorites', (c) => {
  return c.render(
    <div>
      <ul>
        <li>Eating sushi</li>
        <li>Watching baseball games</li>
      </ul>
    </div>,
    {
      title: 'My favorites',
    }
  )
})

MITライセンスでリリースされています。