sensorario sensorario - 3 days ago 6
React JSX Question

ReactJs strange error: Syntax error: Unexpected token (26:39)

This is my example code. I am just trying to execute some code from react documentation. I am trying ti render doubled list of numbers:

import React, { Component } from 'react';

class ListKeysComponent extends Component {
constructor(props) {
super(props);

const numbers = [1, 2, 3, 5, 8, 13];
const doubled = numbers.map((number) => number * 2);

this.state = {
numbers: numbers,
doubled: doubled
};
}

render() {
if (this.state.value > 2000) {
return null;
}

// render numbers in list elements

return (
<div>
<ul>
for (var i = 0; i <= 5; i++) {
<li>{this.state.numbers[i]}</li>
}
</ul>
</div>
);
}
}


But I am not understanding why this code is generating this error message:

Failed to compile.

Error in ./src/ListKeysComponent.js
Syntax error: Unexpected token (26:39)

24 | <div>
25 | <ul>
> 26 | for (var i = 0; i <= 5; i++) {
| ^
27 | <li>{this.state.numbers[i]}</li>
28 | }
29 | </ul>

@ ./src/App.js 22:25-55





edit: the solution from loop inside React JSX

render() {
if (this.state.value > 2000) {
return null;
}

var numrows = this.state.numbers.length;
var list = []
for (var i = 0; i < this.state.numbers.length; i++) {
list.push(<li>{this.state.numbers[i]}</li>);
}

return (
<div>
<ul>
{list}
</ul>
</div>
);
}

Answer

You can't include a for loop inside your JSX markup like that, although it feels like you should be able to. Instead, you can do something like this...

var RepeatModule = React.createClass({
  getInitialState: function() {
    return { items: [] }
  },
  render: function() {

    var listItems = this.props.items.map(function(item) {
      return (
        <li key={item.name}>
          <a href={item.link}>{item.name}</a>
        </li>
      );
    });

    return (
      <div>
        <ul>
          {listItems}
        </ul>
      </div>
    );
  }
});

Here's a post that goes into more detail about how to create repeating pieces of UI in a React component.

Comments