Why does React resolve undefined/boolean/null to string only when they are variables?

  • A+

I'm trying to wrap my head around JSX. I've found a very weird behavior. This is my code:

const name = undefined; const myFunc = () => undefined; let template = (   <div>     {myFunc()}     {name}     {undefined}   </div> );  ReactDOM.render(template, document.querySelector("#root")); 

The output is one time: undefined

Why is the const "name" the only undefined value that is resolved to a string? What is the difference between this const and the other two expressions? (Same with Boolean and null.) Please see my code here: codepen


That's because JSX is syntactic sugar for React.createElement(component, props, ...children)
It will ignore these types (see DOCS):

  • Boolean
  • undefined
  • null

But const name = undefined is not JSX, and as far as i know it will get interpolated as a string.

I just realized that this happens only in codepen because they run the code in the global context and window.name will always be a string.

window.name will convert all values to their string representations by using the toString method.

If you change the variable to something else, lets say name1 it behaves as expected.

const name1 = undefined; const myFunc = function(){return undefined}; let template = (   <div>     {name1}     {undefined}     {myFunc()}   </div> ); 

By the way, stack-snippets behave the same:

console.log('name is ', name); const name = undefined; console.log('and now name is ', name); const name1 = undefined; const myFunc = function(){return undefined}; let template = (   <div>     {name}     {name1}     {undefined}     {myFunc()}   </div> );  ReactDOM.render(template, document.querySelector("#root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div>

Other Editors like codesandbox or jsfiddle will wrap the code in a function, hence there is no conflict with the window.name.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: