JSX is a syntax extension for JavaScript; the name comes from pairing JavaScript and XML together.
Using JSX, we can write HTML-like code inside JavaScript files. It was created by engineers at Meta (formerly Facebook) for React components to be able to represent and render HTML-like markup.
Return a single root element: If we want to return multiple lines of HTML code, we need to enclose them inside a single tag and then return that tag in the react element.
Close tags: In JSX, we must close tags explicitly before rendering the tags. For example, the list items <li>
need to have a closing </li>
tag as seen above.
Camel casing: As JSX is converted into JavaScript, some keywords like event
are reserved keywords, so it is advised to use camel casing as a naming convention such that it becomes eventName
.
Below we can see how to structure our JSX code:
<JSXOpeningElement><JSXChildren><JSXClosingElement>
The syntax is explained in the list below:
We start with the <JSXOpeningElement>
, which is an HTML-like tag that is used to define the element type, e.g. <div>
or <>
.
We then include any children as seen by the <JSXChildren>
tag. Here, we can use nested JSX components or expressions enclosed in {}
curly braces.
At last, we close the JSX element by using a <JSXClosingElement>
tag, which essentially is just a closing tag with the same name as the opening tag, e.g. </div>
or </>
Below we can see an example that uses the structure above:
<div><h1>Hello World</h1></div>
Here the <div>
represents a <JSXOpeningElement>
, the enclosed <h1>Hello World</h1>
represent a child of the <div> element, and finally, we see a </div>
tag that represents the <JSXClosingElement>
tag.
Now that we have gone through what JSX is, we will see how to use JSX with React components, as it was intended for creating dynamic user interfaces using React.
Below is a sample application showing three examples of how React uses JSX for dynamic content rendering.
Below we can see a brief explanation of the code that is used in the application above.
Line 4: We create a name
variable and initialize it with the string Educative
.
Line 5: Then, we use {}
curly braces to enclose the JavaScript variable in an HTML tag using JSX functionalities and save it into a JavaScript variable.
Lines 8–16: To render a web page using multiple HTML tags, we enclose all the tags inside a <div></div>
tag and return it from the component.
Line 9: We also see that we can include a JavaScript object inside the component's returning HTML using {}
curly braces.
Advantages | Limitations |
Can be easily used with component based architectures such as React. | Depends on tools like Babel as it is not natively understood by browsers. |
Easy to understand as it resembles HTML markup. | For large applications, mixing too much JavaScript with HTML can make code hard to manage and scale. |
Integration of JavaScript logic within a HTML-like markup language. | Deeply nested JSX can be hard to maintain. |
Free Resources