Home > database >  Why does JSX parse empty spaces as children
Why does JSX parse empty spaces as children

Time:08-06

I just realized that I can pass empty strings as children in react.

function App() {
  return (
    <Comp> {} {} </Comp>
  );
}

Here is the result directly copy pasted from React Developer Tools.

{
  "children": [
    " ",
    " ",
    " "
  ]
}

I found a Github issue describing this. The issue is closed because that is an expected behavior.

My question is, what is the use case for something like that? Why is this an intended behavior?

CodePudding user response:

Whitespace is text. Text is a node. That's really all there is to it.

And the code has three separate whitespace nodes:

<Comp> {} {} </Comp>
      ^--^--^--- here

How much whitespace is there doesn't make a difference, or what other text is there doesn't make a difference. All that matters in this case is that there are three distinct elements of text (separated by curly braces, which are coincidentally empty but still exists and delineate the text for the parser).

  • Related