Oliver Watkins Oliver Watkins - 1 year ago 118
React JSX Question

JSX does not compile in for loop

The following code does not compile correctly for me as JSX :

let headerText = "";
if (objArgs.column.name instanceof Array) {
headerText = <ul>;
objArgs.column.name.forEach( (item, idx) => {
headerText = headerText + <li> + item + </li>;
return headerText;
}
);
headerText = headerText + </ul>;
}


I just want to create a list out of an array using JSX. The error says that a bracket is out of place. As soon as I remove the JSX elements it works again. Am I using JSX correctly in this snippet?

Answer Source

You are trying to concatenate JSX nodes into a string:

let headerText = "";
...
headerText = headerText + <li> + item + </li>

This is not how JSX works. JSX is not like building an HTML string that gets set with innerHTML. Rather it is an object node structure that React will render to HTML, and JSX < > syntax is just a declarative way to write function calls that return JSX nodes.

What you probably want is something like this:

let headerText;
if (objArgs.column.name instanceof Array) {
  headerText = <ul>
    { objArgs.column.name.map(item => <li>{item}</li>) }
  </ul>;
}

Now you can render the whole headerText somewhere.

Notes:

  • headerText is null (renders empty) or an array of JSX nodes (renders a list).
  • You render valid JS values in JSX using { value }, not + value +.
  • You can just use Array.map() to convert your array to JSX nodes and render them inside another JSX node, like <ul>{ array.map(...) }</ul>. This is the common way arrays are rendered to JSX.
  • Your <li> items should have a key, like <li key={item.id}>. Using the array index as key is not a good idea, and using the item itself is only a good idea if every item is unique (and a primitive value).
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download