adonis, adonisjs, jsx
A AdonisJS v5.x provider for JSX renderer. Use JSX as a templating language on server.
To install the provider run:
npm install @bitkidd/adonisjs-jsx
# or
yarn add @bitkidd/adonisjs-jsx
To configure JSX provider run the command below:
node ace configure @bitkidd/adonisjs-jsx
Then modify your tsconfig.json
file and add two new lines to compilerOptions
section:
(ESNext part is up to you)
"compilerOptions": {
"lib": ["DOM", "DOM.Iterable", "ESNext"],
"jsx": "react-jsx",
}
JSX renderer is exposed in HttpContextContract
and can be used as follows:
...
public async index({ jsx }: HttpContextContract) {
return jsx.render(HelloWorld)
}
...
Or you can access JSX rendered directly and render your component anywhere in the app:
import { JSX } from '@ioc:Adonis/Addons/JSX'
JSX.render(HelloWorld)
A Context
provider is used to pass HttpContext
, props and shared data. The hook that is the most important and can be used to access HttpContextContract
data is useHttpContext
. Using it you can get anything from the context: authenticated used, csrf token, flash messages, i18n and so on. You'll only have to create a custom hook.
import { useHttpContext } from '@ioc:Adonis/Addons/JSX'
const HelloWorld = () => {
const ctx = useHttpContext()
return ctx?.request.csrfToken ?? ''
}
There are some hooks exposed:
useData
that can access data passed to the component when rendering ituseSharedData
that can access data passed to the component usingJSX.share
methoduseHttpContext
that can accessHttpContextContract
The useHttpContext
can be used to create custom hooks based on some HttpContext
data:
import { Context } from '@ioc:Adonis/Addons/JSX'
export const useCsrfToken = () => {
const ctx = useHttpContext()
return ctx?.request.csrfToken ?? ''
}
You can pass and access data passed into components when rendering them.
In your controller:
...
public async index({ jsx }: HttpContextContract) {
return jsx.render(HelloWorld, { hello: 'world' })
}
...
In your component:
const HelloWorld = () => {
const { hello } = useData<{ hello: 'world' }>()
}
Sometimes you need to share some data between all the components and not pass it every time.
In this case you have to create a jsx.ts
file in a /start
folder and then add this jsx.ts
file into .adonisrc.json
in a preloads
section.
Then you can expose some data inside this file:
import { JSX } from '@ioc:Adonis/Addons/JSX'
JSX.share('hello', async () => {
return 'world'
})
And then access it in your components:
const HelloWorld = () => {
const { hello } = useSharedData<{ hello: 'world' }>()
}