user3213604 user3213604 - 5 months ago 6
JSON Question

use of for failing inside return statement inside React render method

The following code is failing with error of 'Unexpected token' pointing at 'for':

import React from 'react';
import ReactDOM from 'react-dom';

export default React.createClass({
render() {
let nodes = JSON.parse(this.props.nodes)
console.log(Object.keys(nodes));

return (
<ol>
{
for (var k in nodes){
let val = nodes[k];
let children = val.children;
let content = val.content;
<li key={k} id={k} content={content} />
// <TChildPane key={k} count={children.length} />
}
}
</ol>
);
}
});


this.props.nodes is passed from the parent component and is an object/hash
which is a collection of objects which contain 'children' and 'content' keys. 'children' key's value is an array. 'content' key's value is a string or bool or int etc...

Please let me know if you see a JSX related error!??

Thanks.

Answer

It's not as easy as it should be to find documentation on what you can and can't do inside jsx, but using for like this is one of those things you can't do. If you want to execute more complex code in place, move it into a function and call the function there instead:

export default React.createClass({
  renderList(nodes) {
    const list = [];
    for (const k in nodes){
      let val = nodes[k];
      let children = val.children;
      let content = val.content;
      list.push(<li key={k} id={k} content={content} />);
    }

    return list;
  }
  render() {
    let nodes = JSON.parse(this.props.nodes)
    return (
      <ol>
        { this.renderList(nodes) }
      </ol>
    );
  } 
});
Comments