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?
varfree floating in a class like that.. think ofclasslike a regular javascript object in that sense, it's a list key values where the values are functions. put thevarabove your class definition