styler styler - 1 year ago 138
React JSX Question

How to loop an object in React?

New to React and trying to loop Object attributes but React complains about Objects not being valid React children, can someone please give me some advice on how to resolve this problem? I've added createFragment but not completely sure where this needs to go or what approach I should take?


var tifs = {1: 'Joe', 2: 'Jane'};
var tifOptions = Object.keys(tifs).forEach(function(key) {
return <option value={key}>{tifs[key]}</option>

Render function

render() {
const model = this.props.model;

let tifOptions = {};

if(model.get('tifs')) {
tifOptions = Object.keys(this.props.model.get('tifs')).forEach(function(key) {
return <option value={key}>{this.props.model.get('tifs')[key]}</option>

return (
<div class={cellClasses}>

<div class="grid__col-5 text--center grid__col--bleed">
<h5 class="flush text--uppercase">TIF</h5>
<select id="tif" name="tif" onChange={this.handleChange}>


Error in console

If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object)

Answer Source

The problem is the way you're using forEach(), as it will always return undefined. You're probably looking for the map() function, 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 something like this:

var tifOptions = [];

Object.keys(tifs).forEach(function(key) {
    tifOptions.push(<option value={key}>{tifs[key]}</option>);

Update: Here's a fiddle showing both options:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download