A Quick Start Guide To JSX

JSX is a JavaScript syntax extension that is primarily used with React to describe what the UI should look like. JSX essentially produces ‘elements’ to render to the DOM.

While JSX may look like a markdown language, we can insert any valid JavaScript expression by placing it inside curly braces. For example:

is equal to:

This is so because after compilation, JSX expressions become regular JavaScript function calls and evaluate to JavaScript objects. This means we can use JSX inside if and for loops, assign it to variables, accept it as arguments, and return it from functions. Here is a deeper look:

evaluates to:

Which essentially creates an object like this:

Something to note: the React DOM uses the camelCase naming convention instead of HTML attribute names. Some typical HTML attributes are also keywords in JavaScript, such as class and for, so different attributes must be used. For example, className instead of class, and htmlFor instead of for.

Lets break down a JSX tag a little deeper. The first part of the tag determines the type of React element that it is. When an element type starts with a lowercase letter, it refers to a built-in component like <div> or <span> and results in a string ‘div’ or ‘span’ passed to React.createElement. Capitalized types indicate that the tag is referring to a React component that must be defined or imported in your file.

Since JSX evaluates to calls to React.createElement after compiling, the React library must always be in the scope of your code.

We can also refer to a React component using dot-notation from within JSX. This is convenient if you have a single module that exports many React components.

Another thing we can put inside a JSX tag is props. If you are unfamiliar with props, start here. We can pass any JavaScript expression as a prop by surrounding it with {}. We can also pass a string literal as a prop, so either of these are valid props:

If no value is passed for a prop, it defaults to true. So the following are equivalent:

As a rule of thumb, it isn’t recommended to pass a prop without value, as things may get confusing. Additionally, true, false, null, and undefined are valid children. They simply don’t render. This can be useful to conditionally render React elements.

If you already have defined props as an object, and you want to pass in JSX, you can use as a spread operator to pass the whole props object. So

is equivalent to

If you’d like a more in depth read on the subject of JSX, try starting here.

Full Stack Software Engineer | Audiophile