Kamyar Parastesh Kamyar Parastesh - 1 month ago 9
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

map
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;
createWord(word){
ID++;
return ({
id:ID,
text:word
});

}

renderList(){

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


To generate the id, I have seen this, and i made the
createWord(word)
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

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>
  </li>);
})