Kamyar Parastesh Kamyar Parastesh - 1 year ago 268
React JSX Question

React: Unexpected token, expected (

I have a react component and i am trying to render a list of string words inside it. I have the words in an array and i can apply

on it. The problem is, I want to set an index as key for every object in the list.
Here is the component:

export default class RandomWords extends Component{

var ID=-1;
return ({



return this.props.words.map((word)=>{
const wrappedText=this.createWord(word);
return (<li key={wrappedText.id} className="item">
<Word value={wrappedText.text}></Word>
// console.log("words are:"+this.props.words);
<ul className="list">

To generate the id, I have seen this, and i made the
function, but in the line
var ID=-1;
it complains with:

Unexpected token, expected (

1-What is wrong with my code?

2-How can i set integer number starting from 0 to the list?

Answer Source

As pointed out in the comments, you can't have vars free floating like that. Regardless, a better solution is to use the built in index of map. Since this is a generator function, the second argument is the index, therefore, you can change your logic to:

return this.props.words.map((word, i)=>{
  return (<li key={i}  className="item">
      <Word value={word}></Word>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download