1

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?

1
  • 2
    you can't put a var free floating in a class like that.. think of class like a regular javascript object in that sense, it's a list key values where the values are functions. put the var above your class definition Commented Nov 1, 2016 at 15:50

2 Answers 2

1

You can only put methods in ES6 classes. Instead, rewrite your class like this:

export default class RandomWords extends Component { constructor(props) { super(props); this.ID = -1; } createWord(word){ this.ID++; return ({ id: this.ID, text: word }); } // ... } 

or, if you want ID to be globally incremented across all instances:

let ID = -1; export default class RandomWords extends Component { createWord(word){ ID++; return ({ id: ID, text: word }); } // ... } 
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.