0

I noticed some inconsistent behavior with React. Take this simple component:

export default function App() {
  const string1 = "A B";
  const string2 = "A B";
  return (
    <>
      {string1}
      {string2}
    </>
  );
}

CodeSandbox

string1 will be rendered to the page as "A B", but string2 is rendered as "A&nbsp;B":

Screenshot

Why does one get rendered as a regular space (U+0020) and the other as a non-breaking space (U+00A0) HTML entity (&nbsp;)? How can I force it to render a regular space in both cases instead of a non-breaking space?

Mike
  • 23,542
  • 14
  • 76
  • 87
  • What do you mean by "breaking space"? A line break? There's a "regular space" (unicode 32), but I don't think "breaking space" is a thing. If I copy your 2 strings, I'm not seeing ` ` on my end. – sallf Mar 05 '21 at 22:47
  • @sallf By "breaking space" I just mean a regular space (U+0020) which allows for automatic line breaks, as opposed to a non-breaking space (U+00A0), which prevents automatic line breaks. Both of these are regular spaces in the source file, but when parsed by the JSX parser, the space in `string2` is converted to the ` ` HTML entity whereas the space in `string1` is not. – Mike Mar 05 '21 at 23:55

1 Answers1

0

I think you have the &nbsp in your "source file". If you delete string2 in your codepen and retype it with your keyboard, &nbsp; goes away. Regular space and non-breaking space   look the same when rendered, but as you observed, if you look at these through the console they will be different.

If you're worried about nbsp ending up on your site, you might either clean the strings in your "source file" or use javascript to find and replace

What's extra confusing, is both typing &nbsp; and pasting a rendered   look identical in your browser's inspector.

nbsp; vs nbsp;

sallf
  • 2,583
  • 3
  • 19
  • 24
  • By golly, you're right. I must have copied and pasted the string thinking it was a regular space. – Mike Mar 07 '21 at 22:20