Skip to main content

Amberley Romo

Developer based in Austin, TX.

2 min read · August 2nd 2019

What is JSX pragma?

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.

An example of this in JavaScript is 'use strict' mode. 'use strict' is a directive that enables JavaScript’s Strict Mode, which is a way to opt in to a more restricted variant of JavaScript. It denotes that the code should be processed in a specific way.

What is JSX pragma?

JSX syntax on its own isn’t readable by the browser. In order to ship something readable to the browser, JSX needs to be converted to plain JavaScript.

Most React-based frameworks (like Gatsby), come with tooling already set up to support this conversion (usually Babel). How does that tooling know how to transform JSX? By default, the Babel plugin will convert JSX into JavaScript that calls the React.createElement function.

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 React.createElement):

  1. Add an option to the Babel plugin
  2. 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?

Using a custom JSX pragma is useful when you want to customize the transform process of JSX => JavaScript.

Further reading

Tagged with themes, theme-uiView all Tags

Enjoyed this post? Receive the next one in your inbox!

Docs
Tutorials
Plugins
Blog
Showcase