Curious Minds

Clear answers to science and history questions

Why JSX Code Formatting Doesn't Work Correctly

· 6 min read · Science

JSX code formatting often fails to work correctly because most formatters and editors do not natively understand JSX syntax, which mixes HTML-like tags with JavaScript expressions in a way that confuses parsers expecting pure JavaScript or pure HTML. When the tool cannot parse the file, it either skips formatting, produces garbled output, or throws errors, leaving your code unformatted or inconsistently styled.

Background: What JSX Is and Why It Breaks Formatters

JSX is a syntax extension for JavaScript, most commonly associated with React, that allows you to write HTML-like markup directly inside JavaScript code. For example:

const element = <h1>Hello, {name}</h1>;

This looks like HTML but is actually transformed into JavaScript function calls (typically React.createElement) by a compiler such as Babel or TypeScript. The problem for formatters is that JSX is not valid JavaScript according to the ECMAScript specification, nor is it valid HTML. It is its own hybrid grammar with rules like:

  • Tags must be closed (self-closing or with an explicit closing tag).
  • Attributes use camelCase (e.g., className instead of class).
  • JavaScript expressions are embedded inside curly braces {}.
  • Fragments (<>...</>) are allowed as shorthand for multiple elements.

A standard JavaScript parser sees <h1> and expects a less-than operator, not a tag. A standard HTML parser sees {name} and treats it as text, not an expression. Only tools with explicit JSX support can handle both worlds correctly.

How Formatters Handle JSX (and Where They Fail)

Most code formatters work by first parsing source code into an abstract syntax tree (AST), then reprinting it with consistent spacing and line breaks. If the parser does not recognize JSX, it will either throw a syntax error or fall back to a generic tokenizer that misinterprets JSX constructs. Common failure modes include:

  • Parser errors: The formatter reports “unexpected token <” and refuses to format the file.
  • Misplaced line breaks: Tags or attributes get split in ways that break JSX semantics, such as breaking a string literal across lines.
  • Lost indentation: Nested JSX elements are flattened or indented incorrectly because the formatter does not understand parent-child relationships.
  • Expression mangling: Curly-brace expressions like {condition && <Component />} may be reformatted into invalid code.

Even formatters that claim JSX support can fail when the file uses newer syntax (e.g., optional chaining, nullish coalescing) or non-standard extensions (e.g., TypeScript’s type annotations inside JSX). The formatter’s parser must be kept up to date with the language features you use.

Common Causes of Incorrect JSX Formatting

When JSX formatting goes wrong, the root cause is usually one of the following:

  1. Formatter lacks JSX support: You are using a tool that only handles JavaScript or HTML, not JSX. For example, some older versions of standard JavaScript formatters did not include JSX parsing by default.
  2. Incorrect file extension: The formatter decides which parser to use based on the file extension. A file containing JSX must have a .jsx or .tsx extension (or be configured explicitly) so the tool knows to enable JSX parsing.
  3. Missing or misconfigured parser plugins: Many formatters (e.g., ESLint, Prettier) require you to enable a JSX plugin or set a parser option. If the plugin is not installed or the configuration is wrong, JSX syntax will be treated as invalid.
  4. Conflicting tools: Running two formatters (e.g., ESLint and Prettier) without proper integration can cause them to fight over the same file, each undoing the other’s changes.
  5. Outdated tool versions: Newer JSX features (like fragments or the new JSX transform) may not be supported by older formatter versions.
  6. Editor integration issues: The formatter may work correctly from the command line but fail inside an editor due to incorrect settings, missing extensions, or workspace configuration overriding global settings.

How to Choose and Configure a JSX-Friendly Formatter

To get reliable JSX formatting, pick a formatter with first-class JSX support and configure it correctly. Prettier is a popular opinionated formatter that handles JSX out of the box. ESLint can also format JSX if you use plugins like eslint-plugin-react and enable the appropriate rules. Here is a general approach:

  1. Install a formatter that supports JSX: Prettier and ESLint (with plugins) are common choices. Ensure you are using a recent version.
  2. Set the correct parser: For Prettier, the parser is inferred from the file extension; for .jsx files it uses babel or typescript with JSX enabled. For ESLint, set parserOptions.ecmaFeatures.jsx to true in your configuration.
  3. Add a configuration file: Create a .prettierrc or .eslintrc file to define rules. For Prettier, you can specify "jsxSingleQuote": true or "bracketSameLine": false to control JSX-specific formatting.
  4. Integrate with your editor: Install the formatter’s extension for your editor and set it as the default formatter for JavaScript and JSX files. Enable “format on save” if desired.
  5. Avoid conflicts: If using both ESLint and Prettier, install eslint-config-prettier to disable ESLint rules that conflict with Prettier’s formatting.

Always test the formatter on a small JSX file before applying it to a large codebase, and check that the output is valid JSX by compiling or running the code.

Alternatives and Workarounds

If your preferred formatter cannot handle JSX, consider these alternatives:

  • Use a different formatter: Switch to one with built-in JSX support, such as Prettier or dprint.
  • Preprocess JSX: Transpile JSX to plain JavaScript with Babel or TypeScript before formatting, then format the output. This is rarely ideal because it loses JSX-specific formatting nuances.
  • Use editor built-in formatting: Some editors have basic JSX formatting built in, though it may be less consistent than dedicated tools.
  • Manual formatting with linting: Rely on ESLint rules to catch style issues without auto-formatting, and format manually.

Each workaround has trade-offs: preprocessing adds a build step, editor built-ins may lack configuration, and manual formatting is error-prone.

Frequently Asked Questions

Why does my formatter break JSX into multiple lines incorrectly?

This usually happens when the formatter does not understand JSX expression containers or attribute boundaries. It may treat the content inside curly braces as plain text and insert line breaks that change the meaning. Ensure your formatter has JSX parsing enabled and is up to date.

Can I use Prettier to format JSX?

Yes, Prettier supports JSX out of the box. It parses JSX correctly and applies consistent formatting. Just make sure your file has a .jsx or .tsx extension or that you have configured Prettier to treat .js files as JSX when needed.

Why does ESLint report parsing errors on JSX?

ESLint’s default parser does not understand JSX. You need to enable JSX in the parser options (e.g., ecmaFeatures: { jsx: true }) or use a parser like @babel/eslint-parser that supports JSX.

Do I need a special file extension for JSX?

While not strictly required, using .jsx or .tsx helps tools automatically detect JSX syntax. If you use .js, you may need to configure your formatter or linter to treat that file as JSX.

Why does formatting change my JSX code’s behavior?

Formatting should never change behavior if the formatter is correct. If it does, the formatter likely misparsed the JSX and produced invalid code. Always review formatted output and run tests to catch such issues.

Can I format JSX inside template literals?

Most formatters do not format code inside template literals (e.g., styled-components). You may need a plugin or a separate tool to handle embedded JSX in tagged template literals.

In this article
  1. Background: What JSX Is and Why It Breaks Formatters
  2. How Formatters Handle JSX (and Where They Fail)
  3. Common Causes of Incorrect JSX Formatting
  4. How to Choose and Configure a JSX-Friendly Formatter
  5. Alternatives and Workarounds
  6. Frequently Asked Questions