Note

JSX is a syntax extension for JavaScript that lets you write HTML-like markup inside a JavaScript file. Although there are other ways to write components, most React developers prefer the conciseness of JSX, and most codebases use it.

Definition

  • JSX is a syntax extension for JavaScript
  • JSX looks a lot like HTML, but it is a bit stricter and can display dynamic information.
  • JSX is very minimal as a templating language because it lets you organize data and logic using JavaScript.

JSX and JS

  • Under the hood it is transformed into plain JavaScript objects
  • Attributes written in JSX become keys of JavaScript objects.
  • Browsers don’t understand JSX out of the box, so we need a JavaScript compiler like Babel or Typescript compiler to transform JSX code into regular JavaScript.
    • Note - Typescript programming language and Transcript compiler are two separate things

Note

JSX and React are two separate things. They’re often used together, but you can use them independently of each other. JSX is a syntax extension, while React is a JavaScript library.

Rules

  • Return a single root element
    • To return multiple elements from a component, wrap them with a single parent tag.
      • Like a <div> or
      • An empty tag <> called a Fragment.
        • Fragments let you group things without leaving any trace in the browser HTML tree.
  • Close all the tags
  • camelCase all most of the things
  • Use className instead of class
    • Since JSX is closest to JavaScript, properties like class in HTML are renamed to className to avoid conflicts with reserved JavaScript keywords.

Curly Braces

A mechanism to use JS inside JSX Used to pass strings, numbers, and other JavaScript expressions

single

double

  • Used to pass object in js
    • JS Object, represented with {} passed inside single one
  • You may see this with inline CSS styles in JSX

[! note] Inline style properties are written in camelCase. For example, HTML <ul style="background-color: black"> would be written as <ul style={{ backgroundColor: 'black' }}> in your component.

Minor Rules

  • Use {} to embed JavaScript expressions

    • Curly braces allow you to evaluate and render variables, functions, or JavaScript expressions directly inside JSX.
  • Use style={{}} for inline styling

    • Inline styles are passed as an object rather than a string, requiring a double set of curly braces (outer braces for the JSX expression, inner braces for the JavaScript style object).
  • Comments in JSX use {/* comment */}

    • Because standard HTML comments (<!-- comment -->) or JavaScript line comments (// comment) inside JSX code can break rendering, JSX comments must be wrapped inside JavaScript expression blocks using /* ... */.