Share


JSX Without React


By gobrain

Jul 11th, 2024

In this article on how to create components in React without using JSX, we have shown you that you can use the react.createElement method to create components instead.

This time, we will discuss how to use JSX without React. Let's get started.

JSX Without React

While JSX is commonly associated with React, it's actually possible to use a similar syntax without the entire React library. Here's a breakdown of how to achieve this:

Since browsers don't understand JSX directly, you'll need a transpiler like Babel to convert it into regular JavaScript function calls. Babel offers a plugin specifically for JSX transformation. You can configure Babel to use a custom function (pragma) instead of React's createElement.

This function will take arguments like the tag name, props, and children, and then create the corresponding DOM elements. Here's a basic example:

function h(tag, props = {}, ...children) {
  const element = document.createElement(tag);
  for (const [key, value] of Object.entries(props)) {
    if (key.startsWith("on")) {
      element.addEventListener(key.slice(2).toLowerCase(), value);
    } else {
      element.setAttribute(key, value);
    }
  }
  children.forEach(child => element.appendChild(child));
  return element;
}

This function creates the DOM element, sets attributes based on props (including event listeners for on prefixed attributes), and appends child elements.

With the transpiler and factory function in place, you can write code that resembles JSX. Remember, this is just syntactic sugar that gets converted to function calls:

const element = h(
  "div",
  { id: "my-element", className: "active" },
  "This is some content!"
);

document.body.appendChild(element);

Libraries and Alternatives:

While building your own JSX factory function works, there are libraries that offer similar functionality:

  • Preact's vhtml: This library provides a lightweight JSX transformation without the overhead of React.
  • Hyperscript (h): Another popular library offering a concise JSX-like syntax for building virtual DOM.

Conclusion

Keep in Mind:

  • Using JSX without React means manually managing the DOM, unlike React's virtual DOM diffing.
  • Consider the trade-offs between a custom solution and established libraries.

Remember, in some cases, it might be simpler to use plain JavaScript for DOM manipulation. But if you prefer the readability of JSX-like syntax, these approaches can be helpful.

Thank you for reading.