165

I understand how (and why) to add a whitespace in JSX, but I am wondering what's best practice or if any makes any real difference?

Wrap both elements in a span

<div className="top-element-formatting">
  <span>Hello </span>
  <span className="second-word-formatting">World!</span>
</div>

Add them on one line

  <div className="top-element-formatting">
    Hello <span className="second-word-formatting">World!</span>
  </div>

Add space with JS

<div className="top-element-formatting">
    Hello {" "}
    <span className="second-word-formatting">World!</span>
</div>
Community
  • 1
  • 1
Jan Swart
  • 6,761
  • 10
  • 36
  • 45
  • 1
    You don't need the extra span, React has fixed long standing issues with text nodes and your second example is fine – Dominic Oct 26 '16 at 13:50
  • 1
    I don't know that there is a defined "best practice" -- certainly you don't need to wrap everything in `` tags, but I generally just follow generic HTML practices when worrying about white space. – arthurakay Oct 26 '16 at 14:00

10 Answers10

161

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>
Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Kevin Ghadyani
  • 6,829
  • 6
  • 44
  • 62
  • 2
    At his point in React's life (v17 2021), if you are here deciding which to use, {'" "} is definitely the better of the two! Or even better, just { } if your linter allows. No spaces needed, but add them if you want the readability. Also mentioned below in undefined's answer. – DORRITO Mar 07 '21 at 21:39
  • 5
    React's official ESLint rules now auto-fix to the proposed `{' '}` in this answer. – Kevin Ghadyani Mar 07 '21 at 22:47
35

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

div {
     white-space: pre-wrap;
}
Milo
  • 3,365
  • 9
  • 30
  • 44
i_code
  • 483
  • 1
  • 5
  • 13
19

I tend to use &nbsp;

It's not pretty but it's the least confusing way to add whitespace I've found and it gives me absolute control over how much whitespace I add.

If I want to add 5 spaces:

Hello&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span className="second-word-formatting">World!</span>

It's easy to identify exactly what I'm trying to do here when I come back to the code weeks later.

Daniel Murawsky
  • 309
  • 1
  • 4
  • 8
    I can't imagine in practice what would be a use of 5 non-breaking spaces that typographically makes sense but aside from such case this is wrong to use in practice. If you are using this for layout, you should use CSS instead and if you need to add a space but don't require it to be non-breaking there are plenty of other spaces that make more typographic sense. See this question, for instance: https://stackoverflow.com/questions/8515365/are-there-other-whitespace-codes-like-nbsp-for-half-spaces-em-spaces-en-space – guioconnor Aug 08 '17 at 08:53
  • 4
    @guioconnor try to extend your imagination and think of an editor application e.g. vscode and you will find that it makes complete typographical sense :D. – Dan May 03 '18 at 11:36
  • this solution makes sense for example when writing data to clipboard so people can paste things into markdown or rtf files. this way developer has some control of empty space rendered in those files. using {' '} works neither for .rtf nor .md files – okram Jul 21 '23 at 12:44
15

You can use curly braces like expression with both double quotes and single quotes for space i.e.,

{" "} or {' '}

You can also use ES6 template literals i.e.,

`   <li></li>` or `  ${value}`

You can also use &nbsp like below (inside span)

<span>sample text &nbsp; </span>

You can also use &nbsp in dangerouslySetInnerHTML when printing html content

<div dangerouslySetInnerHTML={{__html: 'sample html text: &nbsp;'}} />
Idan
  • 3,604
  • 1
  • 28
  • 33
Hemadri Dasari
  • 32,666
  • 37
  • 119
  • 162
14

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):

`${firstName} ${surname}` // Notice this sign " ` ",its not normal quotes.
TheYuriG
  • 134
  • 1
  • 9
Vasyl Gutnyk
  • 4,813
  • 2
  • 34
  • 37
  • In what version of React does this work for you? 15.6.2 seems to ignore this. – smhg Mar 08 '18 at 12:33
  • 1
    @smhg yo. it doesn't depend on version of react. its feautere of ecmascript, typescript. U can type your template in Chrome console to test if your temlate is ok. Problem can be in your babel settings also. – Vasyl Gutnyk Mar 08 '18 at 13:58
  • 1
    You're confusing template literals with JSX expressions. To add a space via JSX, simply put a string consisting of one space character in a [JSX expression](https://reactjs.org/docs/introducing-jsx.html#embedding-expressions-in-jsx). The simplest way to do that is `{' '}`. You don't need template literals for that, though they work (and so does `{" "}`). – Dan Dascalescu Nov 10 '19 at 03:05
  • ye, it was a little bit confusing typo - corrected. Anyway, I'm sure, 99,9% people here are looking for template literals :) – Vasyl Gutnyk Nov 10 '19 at 20:13
  • I like this answer except I'd maybe change the example to something simpler that illustrates usage of a blank space between two variables, e.g. `${firstName} ${surname}`. – Shaun Saker Sep 16 '22 at 10:00
7

I have been trying to think of a good convention to use when placing text next to components on different lines, and found a couple good options:

<p>
    Hello {
        <span>World</span>
    }!
</p>

or

<p>
    Hello {}
    <span>World</span>
    {} again!
</p>

Each of these produces clean html without additional &nbsp; or other extraneous markup. It creates fewer text nodes than using {' '}, and allows using of html entities where {' hello &amp; goodbye '} does not.

undefined
  • 6,208
  • 3
  • 49
  • 59
5

You don't need to insert &nbsp; or wrap your extra-space with <span/>. Just use HTML entity code for space - &#32;

Insert regular space as HTML-entity

<form>
  <div>Full name:</span>&#32;
  <span>{this.props.fullName}</span>
</form>
Andrey Ivlev
  • 85
  • 1
  • 3
  • Side note: today I came across this as [prettier](https://github.com/prettier/prettier) was breaking my code by formatting the space entity. When you use {" "} , it works on a line by itself, and won't break. – gorhawk Feb 05 '19 at 11:34
  • I was just coming in to add this to my own answer. I have upvoted yours instead. – undefined Jan 14 '20 at 02:13
2

use {} or {``} or &nbsp; to create space between span element and content.

<b> {notif.name} </b> <span id="value"> &nbsp;{ notif.count }{``} </span>
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
  • 2
    nbsp = Non-Breakable Space, which is different unicode character from regular space and restricts line breaking. Sometimes that's desirable, just pointing out it's not equivalent to the other options. – Beni Cherniavsky-Paskin Jul 26 '20 at 08:52
1

If the goal is to seperate two elements, you can use CSS like below:

A<span style={{paddingLeft: '20px'}}>B</span>
vcycyv
  • 606
  • 7
  • 9
1

Despite using &nbsp; this is a neat approach: using the <Fragment> tag to insert HTML inside a variable, which allows the creation of a custom spacer to be used in JSX.

Import { Fragment } ...

import { Fragment } from "react"

Create the variable..

const space = <Fragment>&nbsp;&nbsp;&nbsp;&nbsp;</Fragment>

Note: it can also be done with <span> instead of <Fragment>

Use like so..

return ( 
  <div> some text here {space} and here... </div> 
)
Gass
  • 7,536
  • 3
  • 37
  • 41