How to loop an object in React?
The problem is the way you're using forEach()
, as it will always return undefined
. You're probably looking for the map()
method, which returns a new array:
var tifOptions = Object.keys(tifs).map(function(key) {
return <option value={key}>{tifs[key]}</option>
});
If you still want to use forEach()
, you'd have to do something like this:
var tifOptions = [];
Object.keys(tifs).forEach(function(key) {
tifOptions.push(<option value={key}>{tifs[key]}</option>);
});
Update:
If you're writing ES6, you can accomplish the same thing a bit neater using an arrow function:
const tifOptions = Object.keys(tifs).map(key =>
<option value={key}>{tifs[key]}</option>
)
Here's a fiddle showing all options mentioned above: https://jsfiddle.net/fs7sagep/
You can use it in a more compact way as:
const tifs = {1: 'Joe', 2: 'Jane'};
...
return (
<select id="tif" name="tif" onChange={this.handleChange}>
{ Object.entries(tifs).map((t,k) => <option key={k} value={t[0]}>{t[1]}</option>) }
</select>
)
And another slightly different flavour:
Object.entries(tifs).map(([key,value],i) => <option key={i} value={key}>{value}</option>)
you could also just have a return div like the one below and use the built in template literals of Javascript :
const tifs = {1: 'Joe', 2: 'Jane'};
return(
<div>
{Object.keys(tifOptions).map((key)=>(
<p>{paragraphs[`${key}`]}</p>
))}
</div>
)
When I use Object.entries
with map
, I use Array Destructuring like the following and just call them directly.
Object.entries(tifs).map(([key, value]) => (
<div key={key}>{value}</div>
));