48

I have this in some React documentation, as well as screencasts. People will write { " " } inside of their JSX templates.

Why do they do this? It looks like they are using it as an alternative to line breaks, but I don't see that explicitly explained anywhere.

2 Answers 2

75

This is used to put an explicit space in a text block, since leading and trailing spaces are ignored at compile/transformation time when there is another tag.

Example:

<div>
 Text
 <a>some Text</a>
</div>

Will result with Textsome Text on the screen. (see the missing space)

<div>
 Text{' '}
 <a>some Text</a>
</div>

Will result as wanted with Text some Text on the screen.

5
  • I'm not sure that's the example you had in mind. If it is not, can you provide a code example! Jul 24, 2016 at 0:55
  • What's wrong with writing Text <a>some Text</a>? It will keep the white space. Aug 25, 2016 at 10:00
  • 1
    @CosminAbabei Yes, that would keep the whitespace intact, but sometimes your line of text can become quite long, and you need to split it. So the most "obvious" split is on the a tag but that removes the space, so a forced manual space is needed Aug 25, 2016 at 15:16
  • does using &nbsp; not work? or would that have to be wrapped in curly brackets too? like {&nbsp;} Dec 2, 2022 at 21:45
  • 1
    @JeffSpicoli &nbsp; would stay in the compiled code however, it'll lead to a very different behavior than the above. The above ensures to keep a normal breaking space Dec 5, 2022 at 13:28
4

It is used to add some leading or trailing spaces

render() {
  return ( 
    <div>
      My name is{' '}
      <span> Piyush </span>
    </div>
  );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.