How to Use JSX Without React (2024)

JSX gives us a great way to handle HTML-based templating in JavaScript. Did you know you can use it without React?

How to Use JSX Without React (1)

·

Follow

Published in

Better Programming

·

4 min read

·

Jul 29, 2020

--

How to Use JSX Without React (3)

I’m personally a big fan of JSX and love the way it allows me to split up and componentize my code. Even though JSX had been around before React, it wouldn’t have been nearly as popular without React picking it up. However, we can actually use JSX without React, and it’s not that difficult either.

The way React works is by configuring your bundler to convert JSX into calls to a createElement function. So for example:

However, most bundlers allow you to choose your own JSX pragma (function that will be in the place of React.createElement). For example, if you were using Babel, you could specify what function to use through a simple comment like this:

And now Babel would pass those some parameters to myJsxFunction. Now all we need to do is create a function that takes these parameters and creates real DOM nodes that we can add to our DOM. So let’s get started. (If you need a code sandbox to play around in, you can use this static template using standalone Babel.)

DOM nodes are created using the document.createNode() function. It requires just a tag name, so a good place to start would be with that:

Now that we have a DOM node, we have to actually add the attributes provided to us. These can be anything like class or style. So we’ll just loop through all the provided attributes (using Object.entries) and just set them on our DOM node:

This approach has one issue, though. How do we handle events? For example, let’s say I have this JSX:

Our function would set onClick as a normal attribute with the callback set as actual text.

Instead what we can do is check if our attribute starts with on and is in the window scope. This will tell us if it’s an event or not. For example, onclick is in the window scope; however, onfoo isn’t. If it is, then we can register an event listener on that node using the part of the name without the on.

This is how it looks:

Nice! Now all that’s left to do is to add all the children to the parent. However, you can’t append a string to a DOM node, so in case the child isn’t also a node, we can create a text node and append that instead:

However, this quickly runs into issues with deeply nested elements and also elements that are created using array maps. So instead, let’s replace that part with a recursive appendChild method:

And now we can use this in place of our old method:

It works! Try it out. We can now render basic JSX to the DOM:

And you should see your JSX rendered out perfectly. There are a few more things we can add, though; for example, in React, elements are usually functions. Implementing this will allow us to nest components and take full advantage of props, which are a crucial feature of JSX.

Thankfully, it’s pretty simple to implement. All we have to do is check if the tag name is a function instead of a string. If it is, we don’t do any of the other stuff but rather just call the function. Here’s how it looks:

And now let’s try that out:

As you can see, implementing that allowed us to use props as well! You can actually say we’re done here, but there’s one more feature I want to implement: fragments. For those not familiar, fragments are a way to have empty containers in JSX, and they use empty tags. Example:

But for this to work, we need a function that takes this fragment, and instead of creating a DOM element, it just returns its children. Here’s how it looks:

It works out of the box because of our recursive appendChild method.

And that’s it! We’ve done it. A super simple JSX-to-DOM function that lets us use the power of JSX without having to use rReact specifically. You can find the source code for it in this CodeSandbox.

I hope you found this article helpful, I also hope you find some cool ways to use the power of JSX. I actually learned about all of this while working on Dhow, which is a JSX-powered static-site generator for Node.js. It basically lets you write Next.js style code but converts it to static HTML without any hydration qualms.

How to Use JSX Without React (2024)

FAQs

Can we use JSX without using React? ›

JSX is not a requirement for using React.

Each JSX element is just syntactic sugar for calling React. ... So, anything you can do with JSX can also be done with just plain JavaScript.

Do you need React to use JSX? ›

React doesn't require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code. It also allows React to show more useful error and warning messages.

Can I use JSX without React to inline HTML in script? ›

However, we can actually use JSX without React, and it's not that difficult either. The way React works is by configuring your bundler to convert JSX into calls to a createElement function.

Does it matter if you use JS or JSX? ›

Here are the key differences: Syntax: JSX is a syntax extension for JavaScript that allows you to write HTML-like code within JavaScript. It introduces XML-like tags and attributes to create React elements. JS, on the other hand, is plain JavaScript code without any special syntax or extensions.

Do I need to import React in JSX? ›

Upgrading to the new transform is completely optional, but it has a few benefits: With the new transform, you can use JSX without importing React. Depending on your setup, its compiled output may slightly improve the bundle size.

Can I use JSX in Node? ›

Use JSX as a template engine in Node. This module enables requiring . jsx files in Node. It does this by using babel and babel-plugin-transform-react-jsx to first transform jsx into hyperscript, and then transform all h() calls in the resulting hyperscript into more efficient string concatenations.

Why is JSX faster? ›

Why JSX ? It is faster than normal JavaScript as it performs optimizations while translating to regular JavaScript. It makes it easier for us to create templates. Instead of separating the markup and logic in separate files, React uses components for this purpose.

What is the advantage of using JSX? ›

Benefits of Using JSX

JSX enables React to display error and warning messages, which aids in debugging. With JSX, you can write large pieces of code in a more organized and simplified manner. If you have a good understanding of HTML, you'll find it easier to use JSX when developing React applications.

Can a browser read JSX? ›

No, browsers can't understand JSX code. You need a transpiler to convert your JSX to regular Javascript that browsers can understand. The most widely used transpiler right now is Babel.

Can you write HTML in JSX? ›

JSX is an abstraction that allows you to write HTML-like syntax in your JavaScript code and will enable you to build React components that look like standard HTML markup.

Can we use JSX in TypeScript? ›

TypeScript is a popular way to add type definitions to JavaScript codebases. Out of the box, TypeScript supports JSX and you can get full React Web support by adding @types/react and @types/react-dom to your project.

Can you use if statements in JSX? ›

A: No, JSX does not support if-else statements directly. You must use JavaScript expressions, such as the ternary operator, IIFE, or helper functions, to achieve conditional rendering in JSX.

Is it possible to use JSX without React? ›

Each JSX element is just syntactic sugar for calling React. createElement(component, props, ...children) . So, anything you can do with JSX can also be done with just plain JavaScript.

Is JSX necessary to work with React? ›

React doesn't require using JSX, but most people find it helpful as a visual aid when working with UI inside the JavaScript code. It also allows React to show more useful error and warning messages.

Why JSX is better than HTML? ›

Unlike HTML, JSX enables the embedding of JavaScript expressions and facilitates the creation of reusable components, promoting a more dynamic and efficient approach to web development.

Can I use JSX in HTML? ›

JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React.

Can I use Node JS without React? ›

For instance, you can use the EJS templating framework in Node. js to create fully-fledged full-stack applications without using a frontend framework like React. In addition, Node. js is highly scalable, efficient, and flexible.

Can I use React without React DOM? ›

It basically converts all the changes that React identifies in its reconciliation phase into DOM operations. You can use all different kinds of renderers with React. React Native is another one and probably the best known renderer besides ReactDOM. So yes, it is absolutely possible to use React without ReactDOM.

Can we use React without JS? ›

In conclusion, while it is possible to learn React Native without prior knowledge of JavaScript, it is highly advisable to master JavaScript fundamentals first. A solid understanding of JavaScript will make your React Native learning journey smoother and more rewarding.

Top Articles
Everything You Need to Know About the Orbs Syrup Pool on PancakeSwap
Top 5 States Where Retirees Are Moving
Uihc Family Medicine
Black Gelato Strain Allbud
Top Golf 3000 Clubs
Tabler Oklahoma
2021 Tesla Model 3 Standard Range Pl electric for sale - Portland, OR - craigslist
Zoebaby222
Inside California's brutal underground market for puppies: Neglected dogs, deceived owners, big profits
My.doculivery.com/Crowncork
OpenXR support for IL-2 and DCS for Windows Mixed Reality VR headsets
How do you like playing as an antagonist? - Goonstation Forums
Busty Bruce Lee
Uky Linkblue Login
Aris Rachevsky Harvard
Satisfactory: How to Make Efficient Factories (Tips, Tricks, & Strategies)
Nurse Logic 2.0 Testing And Remediation Advanced Test
Gina Wilson All Things Algebra Unit 2 Homework 8
LCS Saturday: Both Phillies and Astros one game from World Series
Loslaten met de Sedona methode
South Bend Weather Underground
Cain Toyota Vehicles
1 Filmy4Wap In
104 Presidential Ct Lafayette La 70503
Walmart Pharmacy Near Me Open
Avatar: The Way Of Water Showtimes Near Maya Pittsburg Cinemas
Gilchrist Verband - Lumedis - Ihre Schulterspezialisten
Klsports Complex Belmont Photos
Pensacola Tattoo Studio 2 Reviews
Gunsmoke Tv Series Wiki
Mini-Mental State Examination (MMSE) – Strokengine
Deepwoken: Best Attunement Tier List - Item Level Gaming
Tire Pro Candler
Td Ameritrade Learning Center
Flags Half Staff Today Wisconsin
Entry of the Globbots - 20th Century Electro​-​Synthesis, Avant Garde & Experimental Music 02;31,​07 - Volume II, by Various
Wilson Tattoo Shops
Lbl A-Z
Obituaries in Hagerstown, MD | The Herald-Mail
Seminary.churchofjesuschrist.org
21 Alive Weather Team
Divinity: Original Sin II - How to Use the Conjurer Class
Gamestop Store Manager Pay
Ehome America Coupon Code
Hk Jockey Club Result
St Vrain Schoology
Centimeters to Feet conversion: cm to ft calculator
The Blackening Showtimes Near Ncg Cinema - Grand Blanc Trillium
Overstock Comenity Login
Electronics coupons, offers & promotions | The Los Angeles Times
Kindlerso
Latest Posts
Article information

Author: Terrell Hackett

Last Updated:

Views: 6445

Rating: 4.1 / 5 (52 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Terrell Hackett

Birthday: 1992-03-17

Address: Suite 453 459 Gibson Squares, East Adriane, AK 71925-5692

Phone: +21811810803470

Job: Chief Representative

Hobby: Board games, Rock climbing, Ghost hunting, Origami, Kabaddi, Mushroom hunting, Gaming

Introduction: My name is Terrell Hackett, I am a gleaming, brainy, courageous, helpful, healthy, cooperative, graceful person who loves writing and wants to share my knowledge and understanding with you.