Why does React resolve undefined/boolean/null to string only when they are variables?
That's because JSX
is syntactic sugar for React.createElement(component, props, ...children)
It will ignore these types (see DOCS):
- Boolean
- undefined
- null
I just realized that this happens only on some editors like 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
.