From HTML to React: A Developer's Guide to JSX
If you're moving from traditional web development to React, JSX can be confusing. This guide explains what JSX is, how it differs from HTML, and why it's so powerful.
For developers coming to React from a traditional HTML and JavaScript background, one of the first and most confusing concepts is JSX. It looks like HTML, but it's written directly inside JavaScript files, and sometimes it behaves in slightly different ways. So, what exactly is it?
What is JSX?
JSX stands for JavaScript XML. It is a syntax extension for JavaScript that allows you to write HTML-like markup inside a JavaScript file. It is not valid JavaScript or HTML on its own. It needs to be compiled (or "transpiled") by a tool like Babel into regular JavaScript objects that React can understand.
For example, this JSX code:
const element = <h1>Hello, world!</h1>;
Gets transpiled into this JavaScript:
const element = React.createElement('h1', null, 'Hello, world!');
This allows you to build your user interface using a familiar, declarative syntax, while still having the full power of JavaScript at your fingertips. You can embed JavaScript expressions directly inside your JSX using curly braces {}.
const name = 'Jphabs';
const element = <h1>Hello, {name}</h1>;
Key Differences Between HTML and JSX
While JSX looks almost identical to HTML, there are a few key differences you need to remember to avoid common errors.
classNameinstead ofclass: Becauseclassis a reserved keyword in JavaScript (used for creating classes), JSX usesclassNameto specify CSS classes. This is probably the most common mistake for newcomers.
<!-- HTML -->
<div class="container"></div>
<!-- JSX -->
<div className="container"></div>
<!-- HTML -->
<div style="background-color: blue; font-size: 16px;"></div>
<!-- JSX -->
<div style={{ backgroundColor: 'blue', fontSize: '16px' }}></div>
Manually converting CSS to a JS object can be tedious. You can use a CSS to Inline Style Converter to automate this.
<br> or <hr> can be written without a closing tag. In JSX, all tags must be closed, either with a separate closing tag or by self-closing with a /> at the end.<!-- HTML -->
<hr>
<img src="...">
<!-- JSX -->
<hr />
<img src="..." />
Getting used to these differences can take a little time, but tools like our HTML to JSX Converter can make the transition smoother by automatically handling these conversions for you.