DEV Community

Cover image for JSX - 0 to Hero
Shani Tiwari
Shani Tiwari

Posted on

JSX - 0 to Hero

key takeaways:

  • Definition: JSX stands for JavaScript XML. It is a syntax extension that allows you to write HTML-like code directly within JavaScript.

  • Role of XML: The "XML" in JSX refers to the ability to define custom tags, providing the flexibility to create reusable UI components.

  • Purpose: It was introduced to solve the problem of separating UI logic from markup, which was common in older template-based libraries. It keeps rendering logic and UI logic in the same place.

  • Readability: JSX serves as a visual aid, making the code more readable and intuitive to write compared to using pure JavaScript functions like React.createElement.

  • JavaScript Integration: You can embed any valid JavaScript expression inside JSX by wrapping it in curly braces.

  • Compilation: Browsers cannot read JSX directly. Tools like Babel act as a translator, converting JSX into JavaScript function calls that produce React elements.

  • Single Parent Requirement: A JSX expression must always return a single parent element. If you need to return multiple items without adding an extra node, you can use React Fragments (empty tags).

  • Camel Case Attributes: Most HTML attributes in JSX must be written in camel case (e.g., onClick), because JSX is closer to JavaScript than traditional HTML.

  • Exceptions: Some attributes like class become className, and for becomes htmlFor to avoid conflicts with JavaScript reserved keywords. Aria and data attributes remain unchanged.

  • Security: JSX helps prevent injection attacks by automatically escaping data, which prevents malicious code from being executed when rendering content.

  • File Extensions: Using a .jsx extension is a hint to build tools like Babel that the file contains JSX code, but it is technically optional if your environment is configured correctly.

Top comments (3)

Collapse
 
jonrandy profile image
Jon Randy 🎖️

JSX is one of the worst ideas in modern web development

Collapse
 
shanitiwari profile image
Shani Tiwari

for pro devs you can say, but for those who started with this - this is probably the best part

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

It was introduced to solve the problem of separating UI logic from markup...

Huh? It does the complete opposite of that - it literally mixes the markup right in there with the code. This is like the bad old days of PHP when HTML was mixed in with application logic.

Most other libraries deal with this much better and keep everything nicely separated.