Best practice when adding whitespace in JSX Best practice when adding whitespace in JSX reactjs reactjs

Best practice when adding whitespace in JSX


Because &nbsp causes you to have non-breaking spaces, you should only use it where necessary. In most cases, this will have unintended side effects.

Older versions of React, I believe all those before v14, would automatically insert <span> </span> when you had a newline inside of a tag.

While they no longer do this, that's a safe way to handle this in your own code. Unless you have styling that specifically targets span (bad practice in general), then this is the safest route.

Per your example, you can put them on a single line together as it's pretty short. In longer-line scenarios, this is how you should probably do it:

  <div className="top-element-formatting">    Hello <span className="second-word-formatting">World!</span>    <span> </span>    So much more text in this box that it really needs to be on another line.  </div>

This method is also safe against auto-trimming text editors.

The other method is using {' '} which doesn't insert random HTML tags. This could be more useful when styling, highlighting elements, and removes clutter from the DOM. If you don't need backwards compatibility with React v14 or earlier, this should be your preferred method.

  <div className="top-element-formatting">    Hello <span className="second-word-formatting">World!</span>    {' '}    So much more text in this box that it really needs to be on another line.  </div>


You can use the css property white-space and set it to pre-wrap to the enclosing div element.

div {     white-space: pre-wrap;}


You can add simple white space with quotes sign: {" "}

Also you can use template literals, which allow to insert, embedd expressions (code inside curly braces):

`${2 * a + b}.?!=-` // Notice this sign " ` ",its not normal quotes.