Iterating through keys of Immutable Map in React
Why not stock.keys()
? As it returns an ES6 iterator, you'll need to cast it to an array for it to work in older JS versions: Array.from(stock.keys())
let zoo = Immutable.fromJS({ 'dog': 1, 'cat': 2 })
zoo.keys().map((name, index) => <Animal name={ name } key={ index } />)
Notice that I avoided key
as a variable and then passed the index
value as key
to the children component, this is because react needs references to dynamically created components so it can handle them correctly within its VirtualDOM. Read more about React's Dynamic Children.
Since you asked this question, a better solution has been posted on the github issue you reference. @vinnymac suggests:
posts.entrySeq().map( ([key, value]) =>
<Post key={key} value={value} />
)
this works well because entrySeq()
returns a Sequence of key/value tuples, which you can then destructure in the params of the .map()
callback.
edit I see now that you are only asking for the keys. In that case use keySeq()
if you want to use ImmutableJS map()
or keys()
if you want to use ES6 map()