How Whitespace Works in JSX

October 3rd, 2015

Familiar with how whitespace works in HTML, but not getting the results you would expect in your React component? Read on.

The easiest way to learn is probably by example, so here we go, example city!

JSX Whitespace === HTML Whitespace

In these examples, HTML and JSX agree on whitespace. Not super interesting - so just scan it and let's move on. For clarity, denotes a single space.

<div>Hello•World</div>
<div>•Hello•World</div>
<div>••Hello•World</div>
<div>•••Hello•World•••</div>
<div>Hello•••World</div>

Remember that even though JSX renders multiple spaces in your HTML, the browser will still collapse sequences of whitespace. (Assuming that the CSS property white-space is left at its default: normal).

All of the above examples are on a single line. When we use multiple lines, JSX & HTML begin to differ.

JSX Whitespace !== HTML Whitespace

Now the good part - this is where JSX won't render your HTML exactly as you typed it. JSX on the left, HTML on the right.

Newlines are removed

<div>••Hello•World</div>
<div>Hello•World</div>

Empty newlines are also removed

<div>••Hello•World</div>
<div>Hello•World</div>

Whitespace removed at the beginning/end of a line

<div>••Hello•World•••</div>
<div>Hello•World</div>
••<div>Hello•World</div>••
<div>Hello•World</div>

Non-breaking spaces can be used to add space

<div>&nbsp;•Hello•World</div>
<div>••Hello•World</div>

In general, the whitespace at the beginning and end of each line is removed, and newlines are removed.

Conclusion

JSX makes it easier to write clean markup without getting extraneous whitespace in your HTML.