If you’re looking into using Theme UI, you’ll come across some (potentially) unfamiliar looking syntax:
This is a JSX pragma. What the heck is a JSX pragma? I had heard the phrase, but not thought too much about it until it came up with Gatsby theming — and lots of other folks hadn't either:
Striking a balance in documentation
In any software project or framework, it can be difficult to define where documentation should start or end. While you might not need to know exactly what a custom JSX pragma is in order to use Theme UI, for example, maybe you want to.
🤔 If we exclude it, will that be distracting? “What the heck is that? I’m going to go down a Google rabbit hole trying to find out.”
🤯 If we include it, will it be overwhelming? “I just want to style a theme, why are you talking to me about pragmas??”
So, a happy medium. If you are interested, here’s a blog post for you!
What is a pragma?
A pragma is a compiler directive. It tells the compiler how it should handle the contents of a file.
'use strict' mode.
What is JSX pragma?
Take the following JSX, for example:
That JSX syntax compiles to a call to
React.createElement, like this:
Other libraries like Preact, Emotion, and Vue.js use different custom functions, and handle JSX differently.
Using a custom JSX pragma
There are two ways to specify a custom function (and therefore replace
- Add an option to the Babel plugin
- Set a pragma comment at the beginning of a module
Add an option to the Babel plugin
Changing the function in the Babel plugin will transform all JSX in an application to use the specified function.
Set a pragma comment
Using a pragma comment will limit the change to the modules the comment is added to. Therefore, you can use
React.createElement by default, and opt in to the custom function only where needed. This is the approach taken in Theme UI.
Why use a custom JSX pragma?
- Emotion uses a custom JSX pragma to use the Emotion
- Theme UI uses a custom JSX pragma to add support for Theme UI's
sxprop, which is used to style elements by referencing values from the theme object.