Skip to content
Tutorials Center
My learning

Topics

React Reference ยท JSX Syntax and Rules

JSX whitespace rules

How JSX trims whitespace: lines are trimmed, blank lines vanish, and spaces between inline elements need {' '} or a same-line layout. With examples.

HTML collapses runs of whitespace into one space. JSX does something different and more predictable: before it compiles your markup, it trims whitespace according to a few fixed rules. Knowing them explains why a word is sometimes glued to the next element, and why indentation never affects the output.

The short version: whitespace that contains a line break at the start or end of a line is removed; spaces on the same line are kept as written.

JSX
<p>
  Hello,
  <b>world</b>
</p>

This renders Hello,world with no space, because the line break and indentation between Hello, and <b> are trimmed away.

Try it

Lines are trimmed
Keeping spaces between elements

Syntax

The rules, applied to text between tags:

Situation Result
Spaces and tabs inside a line of text Kept exactly
Leading and trailing whitespace on a line that has a line break Removed
Lines made only of whitespace Removed completely
Several text lines in a row Joined with a single space
Line break between text and an element No space is inserted
{' '} or {" "} A real space, kept
&nbsp; A non-breaking space, kept

Edge cases: a space between two elements on the same line (<b>a</b> <i>b</i>) is kept. Adjacent expressions such as {last} have nothing between them.

Usage notes

  • Indentation never matters. Move the markup around freely; only line breaks next to text change the result.
  • Add {' '} at the end of a line when a formatter splits text <b>word</b> over several lines and you still want the space. Prettier does this automatically.
  • Rendered spacing is still HTML. Browsers collapse multiple adjacent spaces in normal flow. Use CSS white-space: pre-wrap or &nbsp; when you need several.
  • Line breaks in strings are not trimmed. {'a\nb'} keeps the newline; it displays as one space unless white-space says otherwise.
  • Prefer CSS for gaps. Margins, gap on flex or grid, and padding are more robust than sprinkling {' '}.
  • Joined lines can surprise you. Two lines of text become one two, a single space between them, not a line break. Use <br /> or separate elements for real breaks.