Curriculum
Course: React
Login

Curriculum

React

Text lesson

Expressions in JSX

In JSX, you can include expressions within curly braces { }, which can be React variables, properties, or any valid JavaScript expression; JSX evaluates and returns the result.

Example

Evaluate the expression 5 + 5.

const myElement = <h1>React is {5 + 5} times better with JSX</h1>;

Inserting a Large Block of HTML

To write HTML across multiple lines, enclose the HTML within parentheses.

Example

Create a list containing three items.

const myElement = (
 <ul>
    <li>Apples</li>
    <li>Bananas</li>
    <li>Cherries</li>
 </ul>
);

 

One Top Level Element

The HTML code must be enclosed in a single top-level element. For example, if you want to write two paragraphs, they must be placed inside a parent element like a div.

 

Example

Enclose two paragraphs within a single DIV element.

const myElement = (
 <div>
    <p>I am a paragraph.</p>
    <p>I am a paragraph too.</p>
 </div>
);
JSX will generate an error if the HTML is incorrect or lacks a parent element.

Alternatively, you can use a “fragment”—an empty HTML tag <></>—to wrap multiple lines without adding extra nodes to the DOM.

Example

Enclose two paragraphs within a fragment.

const myElement = (
 <>
    <p>I am a paragraph.</p>
    <p>I am a paragraph too.</p>
 </>
);

Elements Must be Closed

JSX adheres to XML rules, so HTML elements must be properly closed.

Example

Close empty elements with a /> at the end.

const myElement = <input type="text" />;
JSX will produce an error if the HTML elements are not properly closed.