DEV Community

Cover image for What is JSX?
M.Ark
M.Ark

Posted on • Updated on

What is JSX?

JSX, or JavaScript XML, is a syntax extension for JavaScript that allows developers to write HTML-like code within JavaScript.

It's primarily used with React, a popular JavaScript library for building user interfaces. JSX makes writing React components more concise and readable by combining HTML and JavaScript in one place.

Why do we use JSX?

  1. Declarative Syntax: JSX provides a more declarative way to define UI components compared to plain JavaScript. This makes the code easier to understand and maintain.

  2. Component-Based Architecture: React encourages building applications as a collection of reusable components. JSX makes it easy to define these components in a way that resembles the final UI structure, making the code more intuitive.

  3. Integration of HTML and JavaScript: With JSX, you can seamlessly integrate HTML markup and JavaScript logic within the same file, improving code readability and reducing context switching.

  4. Performance Optimization: JSX allows React to perform optimizations like Virtual DOM diffing, which helps in efficiently updating the UI without re-rendering the entire DOM tree.

  5. Static Type Checking: When used with tools like TypeScript or Flow, JSX enables static type checking, catching errors at compile time rather than runtime, thus enhancing code reliability.

Features of JSX

  • HTML-like Syntax: Write HTML tags directly in your JavaScript code.

  • JavaScript Expressions: Embed JavaScript expressions within curly braces {}.

  • Component Nesting: Easily nest components and manage the structure of your UI.

Basic Rules of JSX

  1. Return a Single Root Element Every JSX expression must have a single root element. This means you need to wrap multiple elements in a parent element, like a div, or use React fragments.

Image description
As seen above, the return is under one div element. It acts as the root element.

  1. Close all tags. In JSX, all tags must be closed, even the self-closing ones like
<img />
Enter fullscreen mode Exit fullscreen mode

and

<input />.
Enter fullscreen mode Exit fullscreen mode

Image description
As seen above the image tag has been enclosed within the div tag.

  1. camelCase for Attributes Use camelCase for naming attributes instead of the standard HTML attribute names.

Image description
As seen in the example, we have use the attribute 'className' as opposed to the normal class used in html syntax.

Now lets move further and get to know how to render a list of elements in JSX. Rendering a list of elements in JSX

Top comments (1)

Collapse
 
ark7 profile image
M.Ark

Now lets move further and get to know how to render a list of elements in JSX.

dev.to/ark7/rendering-a-list-of-el...