Custom JSX pragma
JSX is an XML-like syntax extension to JavaScript.
It's a syntax sugar usually used for React's createElement function.
// example JSX
<div>
<Button onClick={handleClick}>Hello</Button>
</div>
React.createElement(
'div',
null,
React.createElement(
Button,
{
onClick: handleClick,
},
'Hello'
)
)
- Most apps use Babel to compile JSX syntax for use with React or other similar libraries.
- By default the Babel plugin will convert JSX into React.createElement.
- Libraries like Preact, MDX, Emotion, and Vuejs use custom create elements functions with JSX.
How to change the underlying create element function?
- add an option to the Babel plugin — will transform all JSX in an application
- set a pragma comment at the beginning of a module — limits the change to only the modules that it's added to
/** @jsx jsx */
import { jsx } from 'my-custom-jsx'
Demo 🚀
What's the stack?
/** convert a style object to a CSS class name */
const className = style({color: 'red'});
CSS-in-Js
Motivation
<span attrs={{ class: style({ color: "blue" }) }} />
// or
<span className={{ "class-1": true, "class-2": true }} />
<p
css={{
margin: 0,
fontSize: 12,
color: 'black'
}}
/>
Emotion,
styled-components,
etc
Custom JSX pragma
By Aleksandra Sikora
Custom JSX pragma
- 1,677