#199: Messing with JSX

Avatar of Chris Coyier
Chris Coyier on

AWS Amplify - the fastest, easiest way to develop mobile and web apps that scale.

Download Video
(Only MVP Supporters can download original high-quality recordings for offline viewing.)

I probably should have learned this long ago, but alas, here we are. Turns out you can tell what function you want JSX to use. Yep, JSX really only has one primary transformation that it does. It turns angle brackets in JavaScript into a function call. So, if you write a line like this in JavaScript:

<div class="big">Hello</div>

After processing (probably with Babel and the JSX plugin), you’ll get, by default:

React.createElement("div", { class: "big" }, "Hello");

But if you include a directive comment telling JSX you want to use your own function, you can change that output:

/* @jsx myFunction */
<div class="big">Hello</div>

Turns into:

/* @jsx myFunction */
myFunction("div", { class: "big" }, "Hello");

That means we can write our own function. Kinda weird, but OK.

The actual use case is for non-React libraries, like Preact. I learned this from looking at Jason Miller’s examples:

Vue can be done this way as well. Note that both Vue and Preact ship this special h function that is designed for this:

Valeri Karpov has some interesting use cases over at their blog post, “An Overview of JSX With 3 Non-React Examples” as well.