Marc Rasmussen
Marc Rasmussen

Reputation: 20555

Use object keys to generate HTML in React

I have the following object:

enter image description here

Now when I try to loop through it:

  {Object.keys(this.state.extras).forEach(key => (
                <div style={{'margin-top': '15px'}}>
                    <Addon data={this.state.extras[key]} addonTitle={key} type={key}
                           selectCallback={this.callbackSelectItem}
                           unSelectCallback={this.callbackUnSelectItem}/>
                </div>
            ))}

No html is displayed.

I have also tried:

let extra;    
Object.keys(this.state.extras).forEach(key => {
    extra += (<div style={{'margin-top': '15px'}}>
        <Addon data={this.state.extras[key]} addonTitle={key} type={key}
               selectCallback={this.callbackSelectItem}
               unSelectCallback={this.callbackUnSelectItem}/>
    </div>);
});

However this returns "[object Object][object Object]"

What have I done wrong?

Update

The object key is extras when I set it on the state.

Upvotes: 0

Views: 715

Answers (1)

Rikin
Rikin

Reputation: 5473

Apart from what's mentioned in comment above by @Chris related to proper usage of extra vs extras in your component which may or may not be bug, main issue of not rendering HTML is below:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

forEach returns undefined, change it to use .map instead.

undefined would not render anything, while array of JSX would render as HTML (it will need key prop)

Furthermore forEach mutates underlying array so use it with caution.

Your code would probably need to be changed like below:

{Object.keys(this.state.extras).map(key => (
  <div style={{'margin-top': '15px'}} key={key}>
      <Addon data={this.state.extras[key]} addonTitle={key} type={key}
             selectCallback={this.callbackSelectItem}
             unSelectCallback={this.callbackUnSelectItem}/>
  </div>
))}

Upvotes: 1

Related Questions