Best practice when adding whitespace in JSX

前端 未结 9 800
粉色の甜心
粉色の甜心 2020-12-02 11:35

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

9条回答
  •  渐次进展
    2020-12-02 12:31

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

      
    Hello World! So much more text in this box that it really needs to be on another line.

    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.

      
    Hello World! {' '} So much more text in this box that it really needs to be on another line.

提交回复
热议问题