Loading lesson path
Concept visual
Start from A
JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React.
JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement()
Formula
and/or appendChild()methods. JSX converts HTML tags into react elements. You are not required to use JSX, but JSX makes it easier to write React applications. Here are two examples. The first uses JSX and the second does not:
const myElement = <h1>I Love JSX!</h1>;createRoot(document.getElementById('root')).render( myElement
);Example »
const myElement = React.createElement('h1', {}, 'I do not use JSX!');createRoot(document.getElementById('root')).render( myElement
);Example » As you can see 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 translated into regular JavaScript at runtime.
With JSX you can write expressions inside curly braces
{ }.The expression can be a React variable, or property, or any other valid JavaScript expression. JSX will execute the expression and return the result:
Formula
5 + 5const myElement = <h1>React is {5 + 5} times better with JSX</h1>;Example »
To write HTML on multiple lines, put the HTML inside parentheses:
Create a list with three list items:
const myElement = (<ul>
Formula
< li > Apples </li >
< li > Bananas </li >
< li > Cherries </li ></ul>
);Example »
top level element. So if you like to write two paragraphs, you must put them inside a parent element, like a div element.
Wrap two paragraphs inside one DIV element:
const myElement = (<div>
Formula
< p > I am a paragraph.</p >
< p > I am a paragraph too.</p ></div>
);Example » JSX will throw an error if the HTML is not correct, or if the HTML misses a parent element. Alternatively, you can use a "fragment" to wrap multiple lines. This will prevent unnecessarily adding extra nodes to the DOM. A fragment looks like an empty HTML tag: <></>.
Wrap two paragraphs inside a fragment:
const myElement = (<>
Formula
< p > I am a paragraph.</p >
< p > I am a paragraph too.</p ></>
);Example »
JSX follows XML rules, and therefore HTML elements must be properly closed.