React has long been a go-to JavaScript library and is easily one of the most popular in the world. Also, with popular frameworks like Next.js and Remix being built on top of React and the ability to do mobile development with React-Native, this library is not going away anytime soon. The problem with this however is that most beginners flock to React and start learning it without really understanding how it works. So let’s dive in.
How JSX Works
In React, JSX (JavaScript XML) is a syntax that looks similar to HTML but works within JavaScript. It’s not valid JavaScript itself, so React uses a transpiler (usually Babel) to convert JSX into standard JavaScript. This JavaScript code is what the browser ultimately interprets.
When you write JSX, it gets transformed into React.createElement()
function calls. These function calls produce React elements, which are the building blocks of a React application. Each element represents a piece of the UI.
Here’s an example of what that looks like:
JSX in a React Component
const element = (
<div>
<h1>Hello, React!</h1>
<p>This is a paragraph.</p>
</div>
);
JSX Transformed into JavaScript:
const element = React.createElement(
'div',
null,
React.createElement('h1', null, 'Hello, React!'),
React.createElement('p', null, 'This is a paragraph.')
);
React takes these nested React.createElement()
calls and converts them into the corresponding HTML elements in the browser’s DOM.
Conclusion
JSX makes writing React components easier by allowing you to write syntax similar to HTML, but it’s just syntactic sugar for React.createElement()
calls that create the structure of your app using JavaScript. This is what allows React to manage the UI efficiently through its Virtual DOM mechanism.
If you enjoyed this article, you might also enjoy my free newsletter I send out every week to developers just like you. You can sign up here.