19

I find out that React.js will condense JSX component HTML tags when rendering, is it possible to avoid this?

For example, I have a jsx component defined in this way:

<div id="wrapper">
  <span>1</span>
  <span>2</span>
  <span>3</span>
</div>

after rendering, it show up in browser this way, condensed:

<div id="wrapper"><span>1</span><span>2</span><span>3</span></div>

I know it is a bit strange for asking such question, but sometimes I just want the component to be rendered as the way I defined it.

And the difference between condensed and not-condensed code:

not-condensed:

enter image description here

condensed:

enter image description here

They are naturally the same code. Although I know that the not-condensed code acts differently from the condensed one because it contains some tab or blank characters, that is originally how we define it.

Maybe it is ridiculous and makes no sense to do this, but I still appreciate any help, thanks!

Eric Zheng
  • 1,084
  • 1
  • 11
  • 23
  • 2
    Can you be more specific about what behavior you're seeing and what behavior you want, and why? – Jordan Running Sep 21 '15 at 03:44
  • This is expected behavior for `inline-block` elements. @insin's answer below is correct; either add white-space manually or change the spans to `display: block;` (though depending on your application that might cause other issues) – pmilla1606 Sep 21 '15 at 13:40

2 Answers2

26

Don’t forget that JSX is just sugar for function calls. So this...

<div id="wrapper">
  <span>1</span>
  <span>2</span>
  <span>3</span>
</div>

...is just sugar for this:

React.createElement("div", { id: "wrapper" },
  React.createElement("span", null, "1"),
  React.createElement("span", null, "2"),
  React.createElement("span", null, "3")
);

If you want whitespace between elements which appear on different lines, you can either add some manually…

<div id="wrapper">
  <span>1</span>{" "}
  <span>2</span>{" "}
  <span>3</span>
</div>

…or open new elements on the same line with whitespace between them (the JSX transpiler respects content between elements, just not linebreaks which are adjacent to elements):

<div id="wrapper">
  <span>1</span> <span>2</span> <span>3</span>
</div>

…both of which transpile to this:

React.createElement("div", { id: "wrapper" },
  React.createElement("span", null, "1"),
  " ",
  React.createElement("span", null, "2"),
  " ",
  React.createElement("span", null, "3")
);
Rory O'Kane
  • 29,210
  • 11
  • 96
  • 131
Jonny Buchanan
  • 61,926
  • 17
  • 143
  • 150
0

If it's appropriate, you can use display: inline-block with side margin equal to the space width:

#wrapper span {
  display: inline-block;
  margin-right: 0.28em;
}
Distagon
  • 1,018
  • 11
  • 14