React Design Patterns and Best Practices(Second Edition)
上QQ阅读APP看书,第一时间看更新

Spaces

There's one thing that could be a little bit tricky in the beginning and, again, it concerns the fact that we should always keep in mind that JSX is not HTML, even if it has an XML-like syntax.

JSX handles the spaces between text and elements differently from HTML, in a way that's counter-intuitive.

Consider the following snippet:

  <div> 
<span>My</span>
name is
<span>Carlos</span>
</div>

In the browser, which interprets HTML, this code would give you "My name is Carlos", which is exactly what we expect.

In JSX, the same code would be rendered as MynameisCarlos, which is because the three nested lines get transpiled as individual children of the div element, without taking the spaces into account. A common solution to get the same output is putting a space explicitly between the elements as follows:

  <div> 
<span>My</span>
{' '}
name is
{' '}
<span>Carlos</span>
</div>

As you may have noticed, we are using an empty string wrapped inside a JavaScript expression to force the compiler to apply the space between the elements.