AdonisJS package for adding JSX as your templating engine
npm install adonisjsx- JSX as a runtime, usable everywhere in your app
- Config for global layouts
- Extended HTTPContext with jsx rendering and streaming methods
- Vite integration
- Uses @kitajs/html for JSX runtime
``bash`Install the package
npm i adonisjsxRegister providers and config
node ace configure adonisjsx$3
After installing package, extend your tsconfig.json compiler options:
`json`
{
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "@kitajs/html",
// Optionally add the ts-html-plugin for xss protection
// the package is installed automatically if you are using adonisjsx
"plugins": [{ "name": "@kitajs/ts-html-plugin" }]
}
}
to true if you want to access helpers that depend on HttpContext to work.
$3
`tsx
const Component() {
return Hello World
}router.get('/', async ({ jsx }) => {
return jsx.render(Component)
})
router.get('/stream', async ({ jsx }) => {
jsx.stream(Component)
})
`API
With the JSX configured, whenever you use it will be compiled to string, so you can simply return JSX from your routes, controllers, or any other place in your app. However, it may get tedious if you are accustomed to using layouts or you want to use more powerful features like streaming. The package gives you a few tools to make your life easier.
$3
`tsx
render: <
TData extends Record,
TOptions extends {
layout?: Component
data: TData
},
>(
view: Component | string,
options?: TOptions
) => Promise
`
You can render your components with the jsx util. It will wrap your component with global layout by default (which you can override through options or change it globally in the jsx.ts config published by the package). `tsx
// routes.tsx
import { MyComponent, Layout } from '#components'
route.get('/', async ({ jsx }) => {
return jsx(MyComponent)
// If your component takes props, data option will be typed accordingly
return jsx(MyComponent, { data: { name: 'John' }, layout: Layout })
})
`$3
`tsx
stream: , TOptions extends {
layout?: Component;
errorCallback?: (error: NodeJS.ErrnoException) => [string, number?];
data: TData;
}>(view: Component rid?: number | string;
}>, options?: TOptions) => void
`You can
await any data in the component normally, as they are not react components but just functions that are converted from syntax sugar into pure javascript. `tsx
async function MyComponent() {
const data = await fetch('https://api.com/data')
return {data}
}
`But you may want to show most of your UI instantly, and then stream only the parts that require async data. You can do that with
render method. It will render the component and then stream the async parts as they resolve. Underneath, this method uses AdonisJS streaming, so you do not return the result of the method, you just call it.stream takes the same options as render method, but also accepts errorCallback option, which is called when an error occurs during streaming. By default, it will log the error and send 500 status code, but you can override it to handle errors in your own way. It comes directly from the framework streaming methods. The method will also pass the render id to your component - through rid prop that you can pass to the Suspense component as unique identifier. If you want to, feel free to generate one yourself.`tsx
import { Suspense } from 'adonisjsx'router.get('/', async ({ jsx }) => {
jsx.stream(MyComponent, { errorCallback: (error) => ([
Rendering failed: ${error.message}, 500]) })
})function MyComponent({ rid }) {
return (<>
Instant UI
rid={rid}
fallback={Loading username...}
catch={(err) => Error: {err.stack}}
>
>)
}async function MyAsyncComponent() {
const data = await fetch('https://api.com/data')
return
{data}
}
`$3
`tsx
async function viteAssets(entries: string[], attributes: Record = {}): JSX.Element
`
If you use vite with AdonisJS, there are helper methods for edge templates that integrate your templates with vite. adonisjsx provides similar helpers for JSX. You can use
viteAssets method to generate resource tags in your JSX that refer to the vite entries.For vite config like this:
`tsx
adonisjs({
entrypoints: ['resources/js/app.js'],
})
`You can add the javascript entry to your JSX like this:
`tsx
import { viteAssets } from 'adonisjsx'async function MyComponent() {
return (
{await viteAssets(['resources/js/app.js'])}
Hello World
)
}
`
$3
`tsx
async function viteReactRefresh(): JSX.Element
`This function will add the necessary script tags to enable vite's react refresh feature. Make sure it is registered before actual react scripts.
`tsx
import { viteReactRefresh, viteAssets } from 'adonisjsx'async function MyComponent() {
return (
{await viteReactRefresh()}
{await viteAssets(['resources/js/app.js'])}
Hello World
)
}
`$3
With @adonisjs/shield installed, you can use csrfField method to generate a hidden input with csrf token.`tsx
import { csrfField } from 'adonisjsx'function Form() {
return (
)
}
`$3
You can use route method to generate urls for your routes. It works the same way as in edge templates.`tsx
// routes.tsx
import router from "@adonisjs/core/services/router";router.get('/foo', async () => {
return "foo"
}).as('foo')
``tsx// MyComponent.tsx
import {route} from 'adonisjsx'
function MyComponent() {
return (
Home
)
}
`Recipes
Code samples that will help you move from edge templating.$3
You may need to access request or other HttpContext metadata inside your component. You can do that by calling HttpContext.getOrFail method.`tsx
function MyComponent() {
const { request } = HttpContext.getOrFail()
return {request.ip()}
}
``