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:
Do you know what "jsx pragma" is?— amberley (@amber1ey) July 22, 2019
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!
A pragma is a compiler directive. It tells the compiler how it should handle the contents of a file.
'use strict' mode.
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.
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
Changing the function in the Babel plugin will transform all JSX in an application to use the specified function.
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.
- 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.