user2861799 user2861799 - 3 months ago 9
React JSX Question

Why does adding a space in tag register the node as Comment_Node

I have the following piece of test code that is used with jest I load the React component in the "Dom".

const actionDropDownErrorNode =(data,myStyles={})=>{
let actionDropDownErr = TestUtils.renderIntoDocument(
<div><ActionDropDownError data={data || <div></div>} styles={myStyles}/></div>
);

return ReactDOM.findDOMNode(actionDropDownErr).firstChild;
};


now when I check the contents of the element

<span className={styles.solution || "solution"}>{data.solution}</span>


it returns a Text_Node which is what I want but if I alter the element to:

<span className={styles.solution || "solution"}>{data.solution} </span>


it returns a Comment_Node why is that ?

For reference purpose this is how I get the data.solution out of the element tag:

const elementContent = node =>{
if (node.nodeType === 1 && node.firstChild !== null) {
if (node.firstChild.nodeType ===3){
elements.push(node.firstChild.textContent);
}

}


};

Answer

A space in JSX result to an empty string " ":

So this <span className={styles.solution || "solution"}>{data.solution}</span> will result to :

React.createElement(
  "span",
  { className: styles.solution || "solution" },
  data.solution
);

and this <span className={styles.solution || "solution"}>{data.solution} </span> will result to :

React.createElement(
  "span",
  { className: styles.solution || "solution" },
  data.solution,
  " "
);