#199: Messing with JSX

Programming - Mar 31, 2024

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.

Previous Next
Copyrights
We respect the property rights of others, and are always careful not to infringe on their rights, so authors and publishing houses have the right to demand that an article or book download link be removed from the site. If you find an article or book of yours and do not agree to the posting of a download link, or you have a suggestion or complaint, write to us through the Contact Us .
Read More