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
Dogecoin Is Up 1,000% in a Month. Is It a Good Investment Yet? | The Motley Fool
Two Years Into Our Mortgage: How's It Going? — Summit of Coin
855 700 4473
S&W My Chart
Oak Lawn Patch News
Nederland Police Department arrests and responses: Oct. 2-8 - Port Arthur News
Ticket To Paradise Showtimes Near Apple Cinemas Waterbury
Epidermis Function: How Skin Protects You and How You Can Protect It
Dr Matheson Waco Tx
Hypno Deviantart
Fab Last Minute Cruises
Citibank Branch Locations In Orlando Florida
Blueway Truck Sales
Wink Ice Cream Net Worth
Preppy Bio Generator
Headlining Hip Hopper Crossword Clue
Which Country Has Hosted A Summer Olympics Microsoft Rewards
Craigslist Ocala Garage Sales
Jobs Hiring 18 Year Olds Near Me
Rubmaps Las Vegas
Oral-B iO 8N Elektrische Tandenborstel Zwart
Locate Td Bank Near Me
SpeechWire Tournament Services
Griffin Exterminating New Bern Nc
Mayas Mexican Pell City
Stellaris Wargoal
The Voice Season 22 Wiki
Tj Nails Victoria Tx
Fisher-Cheney Funeral Home Obituaries
26200 E 64Th Ave
Hca Florida Middleburg Emergency Reviews
Obituary for GARY ALAN YOUNGS | After®
Megan Olivia Hall Facebook
Alles over de app MSN Weer
Fapptime.cc
Craigslist Lake Charles
Portugal Anúncios Classificados OLX
Prinzessin Lillifee Muffins Rezepte | Chefkoch
Happy Ending Massage Augusta Ga
High Temp Yesterday Near Me
Fgo Spirit Root
80 For Brady Showtimes Near Regal Largo Mall
24 Hour Arrest List Knox County
Joes Barbershop Maricopa Az
Find The Difference: Mc002-1.Jpg
U-Shaped Cleat Crossword
Best Gk Fifa 22
2021 GMC Sierra 2500HD AT4 4x4Crew diesel for sale - Kernersville, NC - craigslist
Craigslist Pet Phoenix
Oppenheimer Showtimes Near Cinemark Denton
Round Cake Pans Walmart
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.