Skip to main content

JSX Middlewares

JSX Middlewares allows you to change the behavior of JSX renderer by adding middlewares. This allows you to enhance JSX with additional features that were not possible before, such as adding support for custom attributes and Angular-like directives.

Installation

npm install jsx-middlewares

Setup your JSX transpiler

To use JSX Middlewares, you need to setup your JSX transpiler to use the jsx-middlewares/react package as the JSX factory. This is done differently depending on the transpiler you are using.

tsconfig.json
{
"compilerOptions": {
"jsxImportSource": "jsx-middlewares/react"
}
}

Usage

Firstly, you need to add middlewares at the start of your application.

main.jsx
import { addMiddlewares } from 'jsx-middlewares/react';

addMiddlewares(function emojiMiddleware(next, type, props, key) {
// Modify the props to add an emoji to the text
if (typeof type === 'string' && typeof props.children === 'string') {
props = {
...props,
children: props.children + ' 🎉',
};
}

// Call the next middleware with the new props
// If there is no next middleware, it will call the original JSX renderer
return next(type, props, key);
});

Then, you can write your JSX as usual.

my-file.jsx
export function App() {
return (
<div>
<h1>Hello World</h1>
<p>This is a paragraph</p>
</div>
);
}

The output will be like this:

http://localhost:3000

Hello World 🎉

This is a paragraph 🎉

What's next?

For more examples of what you can do with JSX Middlewares, check out the examples section.