แนวทางปฏิบัติที่ดีที่สุดเมื่อเพิ่มช่องว่างใน JSX


96

ฉันเข้าใจวิธี (และทำไม ) ในการเพิ่มช่องว่างใน JSX แต่ฉันสงสัยว่าแนวทางปฏิบัติที่ดีที่สุดคืออะไรหรือมีข้อแตกต่างที่แท้จริงอย่างไร

รวมทั้งสององค์ประกอบในช่วง

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

เพิ่มในบรรทัดเดียว

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

1
You don't need the extra span, React has fixed long standing issues with text nodes and your second example is fine
Dominic

1
I don't know that there is a defined "best practice" -- certainly you don't need to wrap everything in <span> tags, but I generally just follow generic HTML practices when worrying about white space.
arthurakay

คำตอบ:


110

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>

14

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

div {
     white-space: pre-wrap;
}

If the container is flex, then you'll need this solution.
Curtis

This is the only non-&nbsp; solution that worked for me!
Magnus

@Magnus You're welcome, my man. None of the solutions to this answer actually worked for my special case.
i_code

10

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.

In what version of React does this work for you? 15.6.2 seems to ignore this.
smhg

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

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. The simplest way to do that is {' '}. You don't need template literals for that, though they work (and so does {" "}).
Dan Dascalescu

ye, it was a little bit confusing typo - corrected. Anyway, I'm sure, 99,9% people here are looking for template literals :)
Vasyl Gutnyk

6

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.


6
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: stackoverflow.com/questions/8515365/…
guioconnor

2
@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

6

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.


4

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>

Side note: today I came across this as 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

I was just coming in to add this to my own answer. I have upvoted yours instead.
undefined

4

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;'}} />

2

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

<b> {notif.name} </b> <span id="value"> &nbsp;{ notif.count }{``} </span>

1
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

0

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

A<span style={{paddingLeft: '20px'}}>B</span>

This only offers visual, not semantic separation. If you copy the result, you're still getting AB, not A B.
ΔO 'deltazero'
โดยการใช้ไซต์ของเรา หมายความว่าคุณได้อ่านและทำความเข้าใจนโยบายคุกกี้และนโยบายความเป็นส่วนตัวของเราแล้ว
Licensed under cc by-sa 3.0 with attribution required.