The Basics of JSX

JSX is a funny animal. It was born out of React and is very much the water that React developers swim in.

“JS” means it’s Javascript (or TypeScirpt, if you are writing TSX), but the X makes it like XHTML. XHTML is the HTML standard that that makes “HTML” more like XML. If you’re new to programming, you’re probably wonder, what’s important about all of these standards and why is this relevant.

• XML is a markup that must be “well formatted.” This essentially means that all tags must be closed. Closing many tags, like </body> or </div> makes sense but there are some tags which sometimes, lazy HTML developers will allow the well-known “forgiveness” of HTML to do something dirty: Not self-close your single tags. For example, writing <br> or <image> tags. Technically, what makes it XHTML is that all tags must either have closing tags or be self-closing (a self-closing tag would look like: <br /> or <image src="..." />

So now that we know that XHTML means that we must either close every tag or self-close tags, we know that JSX also behaves this way: Even in your normal-looking HTML, you can’t have tags that don’t self close.

Here are some things to keep in mind when working with JSX:

  1. You are working in what looks and acts like Javascript, except things that are HTML-like get turned into their corresponding React or HTML components.

2. A React fragment is a way to create a conceptual React container without creating an output HTML element. This trick is found often and looks like this:

3. When inside of an XHTML block, you can then re-escape back into Javascript using { and }

4. JSX, unlike markup languages, does not support if statement, or another kind of Javascript block structure, around HTML-like things. If you have some content that you want to display only in certain conditions, you have two options: 1) Check the condition before the rendered content and then assign the block to a local variable that is displayed to the screen. 2) Use the condition render.

5. The opening and closing braces must contain a complete Javascript expression, which will get evaluated and output into the markup.

6. Within the escaped { and }, we can also use string interpolation which themselves may contain { and }. This subtle effect of JSX is probably its most powerful feature.