JSX without React

 A screenshot of a source code file with JSX code.

For me JSX is the part of React that makes developing with it a real treat. Yes, the functional nature, the state and lifecycle management are really nice, too, but JSX makes it all come together in a great way. The effortless integration of HTML inside of JavaScript just makes it one of the best experiences writing a web frontend.

const element = (
  <h1 className="greeting">
    Hello, world!
  </h1>
);

Sadly for my current side project React was not a great fit. I wanted something smaller. Something that could progressively enhance the website. It was important that everything also works without JavaScript and loaded fast. React was a no go for me.

I tried a few things and decided to give Stimulus a chance. After a few hours I realized I really wanted to use JSX inside of my new project, too. But how?

Luckily there already was a little library that did just that: adding JSX capabilities to projects without React. It was just a small tech demo, but I was able to add a couple of missing features with just a few lines of code. After two PRs the maintainer Terry allowed me to take over the project and it now lives inside of my GitHub account 😍.

How does it look like?

import { Controller } from "stimulus";
import jsxElem, { render } from "jsx-no-react";

export default class extends Controller {
  connect = () => {
    render(<div>
      Stimulus version of this element
    </div>, this.element);
  };
}

Isn’t that nice? Jump over to the readme to see how you can add it to your own projects.

How it works? That’s not as complicated as it might seem. Turns out that you just need a babel plugin that transforms your JSX tree into a method call. Babel transforms the example from the beginning into this:

const element = React.createElement(
  'h1',
  {className: 'greeting'},
  'Hello, world!'
);

The only part missing is the implementation of that method. The implementation is pretty straight forward.

After building my project with it I have to say that I really love the mixture of Stimulus and JSX.

If you want to see the end result or ever wanted to have a platform neutral wishlist outside of Amazon, feel free to give Wishlephant a try.

Portrait photo of Bodo Tasche
Bodo Tasche
Polyglot Developer

I am a freelance polyglot developer and love HTML5, testing, TypeScript, Ruby and Elixir. In the last 20 years I have been in lots of different roles, from Java to Elixir, from backend developer at a 3 people team in an early phase startup to the CTO of a web agency. Some of my work can be seen on my projects page.

Need help developing your MVP or to add new features into your current app? Need a CTO or a front/backend developer for hire? Send me an email.