johno

What is pragma?

For a lot of us building for the web, whether you're using React, Preact, Vue, Emotion, MDX, or another library that uses JSX you've been using a JSX pragma. Possibly without ever realizing it!

In Computer Science speak it's a "directive" that tells a compiler how to handle the input.

In Ruby, you can do something like:

# coding: UTF-8

def foo
  :bar
end

The key: value notation is used by the Ruby interpreter. The above tells Ruby to use UTF-8 encoding.

In JavaScript, outside the context of JSX, there's a "pragma" to use strict mode: "use strict".

Back to JSX

Babel now supports JSX by default and will transform JSX to the proper function call. In a React project, the following JSX:

const TomatoBox = (
  <div
    style={{
      backgroundColor: 'tomato',
      padding: '20px'
    }}
  >
    I'm Tomato!
  </div>

Would result in:

const TomatoBox = React.createElement(
  'div',
  {
    style: {
      backgroundColor: 'tomato',
      padding: '20px'
    }
  },
  "I'm Tomato!"
)

This occurs because most projects will use @babel/plugin-transform-react-jsx which sets a default pragma of /* jsx React.createElement */. That's why we end up with the React.createElement function call.

Changing the pragma

When babel transpiles JSX it checks for a pragma, or directive, which might look like:

/* jsx h */
const TomatoBox = (
  <div
    style={{
      backgroundColor: 'tomato',
      padding: '20px'
    }}
  >
    I'm Tomato!
  </div>

Even using @babel/plugin-transform-react-jsx, we'd result in h() function calls because it takes precedence during babel's transpilation.

const TomatoBox = h(
  'div',
  {
    style: {
      backgroundColor: 'tomato',
      padding: '20px'
    }
  },
  "I'm Tomato!"
)

Conclusion

Often times the "Computer Science" speak doesn't make it easy to parse what's actually happening. Sometimes using simpler words is better. I'll go with:

It's a fancy name for mapping function calls in JSX

me, one day on a Zoom call

Related