React JSX

JSX stands for JavaScript XML and it allows us to write HTML directly within React. This makes it easier to create and manage HTML structures within React applications.

Tutorials dojo strip

Coding with JSX

JSX allows us to write HTML elements directly in JavaScript and place them in the DOM without using createElement() and/or appendChild() methods. JSX converts HTML tags into React elements. While using JSX is not mandatory, it simplifies writing React applications.

Here are two examples: one with JSX and one without.

In the first example, JSX allows us to write HTML directly within the JavaScript code. JSX is an extension of the JavaScript language based on ES6 and is converted into regular JavaScript at runtime.

Using JSX

JavaScript

Without JSX

JavaScript

Expressions in JSX

With JSX, you can write expressions inside curly braces {}. These expressions can be React variables, properties, or any valid JavaScript expressions. JSX will execute the expression and return the result.

JavaScript

Inserting a Large Block of HTML

To write HTML over multiple lines, enclose the HTML code within parentheses.

JavaScript

One Top Level Element

The HTML code must be wrapped in a single top-level element. If you need to write two paragraphs, place them inside a parent element, such as a <div>.

Wrap two paragraphs inside a <div> element EXAMPLE

JavaScript

JSX will throw an error if the HTML is not correctly structured or missing a parent element. Alternatively, you can use a “fragment” which prevents adding unnecessary nodes to the DOM.

A fragment looks like an empty HTML tag: <></>.

JavaScript

Elements Must Be Closed

JSX follows XML rules, so HTML elements must be properly closed. JSX will throw an error if the HTML elements are not properly closed.

JavaScript

Attribute class = className

The class attribute is commonly used in HTML. However, since the class keyword is reserved in JavaScript, JSX uses className instead. When JSX is rendered, className attributes are converted to class attributes.

JavaScript

Conditions – if Statements

React supports if statements but not inside JSX. To use conditional statements in JSX, place the if statements outside the JSX or use a ternary expression.

Option 1: Write if statements outside JSX:

JavaScript

Option 2: Use ternary expressions:

When embedding a JavaScript expression in JSX, remember to wrap the JavaScript with curly braces {}.

JavaScript

Tutorials dojo strip