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!
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.
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.
<div>••Hello•World</div>
<div>Hello•World</div>
<div>••Hello•World</div>
<div>Hello•World</div>
<div>••Hello•World•••</div>
<div>Hello•World</div>
••<div>Hello•World</div>••
<div>Hello•World</div>
<div> •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.
JSX makes it easier to write clean markup without getting extraneous whitespace in your HTML.