DEV Community

SavvyShivam
SavvyShivam

Posted on

Introduction to JSX

Introduction to JSX

JSX is basically a syntax extension of regular JavaScript and is used to create React elements. These elements are then rendered to the React DOM.

Let us see a sample JSX code:

Why JSX?

  • It is faster than normal JavaScript as it performs optimizations while translating to regular JavaScript.

  • It makes it easier for us to create templates.

  • Instead of separating the markup and logic into separate files, React uses components for this purpose.

In React we are allowed to use normal JavaScript expressions with JSX. To embed any JavaScript expression in a piece of code written in JSX we will have to wrap that expression in curly braces {}.

Consider the following piece of code:

**Output**
Enter fullscreen mode Exit fullscreen mode

In the above program we have embedded the javascript expression const name = “Geeks”; in our JSX code. We embed the use of any JavaScript expression in JSX by wrapping them in curly braces.

JSX Expressions

Expressions are also supported in JSX, which is written in JavaScript syntax. The expressions are enclosed in curly brackets. Expressions can contain conditional statements like if-else and for loops. The following code is an example of JSX Expression:

**Output**
Enter fullscreen mode Exit fullscreen mode

JSX Attributes

JSX allows us to use attributes with the HTML elements just like we do with normal HTML. But instead of the normal naming convention of HTML, JSX uses the camelcase convention for attributes. For example, class in HTML becomes className in JSX. The main reason behind this is that some attribute names in HTML like ‘class’ are reserved keywords in JavaScript. So, in order to avoid this problem, JSX uses the camel case naming convention for attributes.

Output:
Enter fullscreen mode Exit fullscreen mode

Comments in JSX

JSX allows us to use comments as it allows us to use JavaScript expressions. Comments in JSX begins with /* and ends with */. We can add comments in JSX by wrapping them in curly braces {} just like we did in the case of expressions. Below example shows how to add comments in JSX:

Top comments (0)