Bars Icon

Intro to JSX: HTML that does JavaScript

29-12-2023 11:38 AM

JSX is a way to write HTML inside of JavaScript, but it feels more like a way to write JavaScript inside of HTML. As a templating language, it is beloved by some and loathed by others. Here’s a look at how it works and why it’s important.

JSX was introduced as a templating language for the wildly popular React framework. It gives you a way to define the structure of an application view with HTML markup that interacts with the application’s JavaScript context. This simple notion flies in the face of conventional wisdom about separating the view from the behavior, which is why developers tend to either love it or hate it.Ignoring the controversy about JSX in principle, we can focus on the question of how to use it. JSX is the de facto standard for reactive templating engines, and inspires those used by others such as Vue, Svelte, and so on. Here’s what basic JSX looks like in a React application (see the live version):

If you look at everything inside the <div>, you’ll see it is just HTML. It is, however, wrapped inside of JavaScript. The HTML is a return value for the App function, which is a functional component in React. The JSX markup is the function’s return value. In essence, the JSX return value tells the React render engine what the component’s output is.

Once upon a time, it was strange to see markup inlined into JavaScript, but now it is commonplace. In fact, it is very convenient to have the markup and JavaScript together. Let’s say we want to introduce a variable into the markup. We could do it like so (see the live version):

Now we are using the “name” variable inside the JSX. The name variable is created using the React.useState hook, but it could be any JavaScript variable as long as it is in scope. (When using functional components, the useState hook is the correct way to use a variable in JSX.).The curly braces around name in the JSX template denote a JSX expression. They allow you to execute JavaScript expressions inside the markup as well as referring to variables. The JavaScript executes within the larger context of the surrounding code— that’s why you can reference the variables.
Now we start to see some of the power that has made JSX so successful. You get all the facilities of JavaScript, imported libraries like the React framework, and a complete HTML syntax that can reference these features.Notice that JSX can use expressions, but not full JavaScript. It will output the result of the expression to the view in the place it is found in the template. Things that don’t return a value, like loops, don’t work. (This is different from some other templating tools.)