0

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.

3
  • 1
    It seems to be extra and not extras? It also seems to be an array, not an object Commented Feb 14, 2020 at 14:00
  • First of all extra is not an object its an array. And extra[0] is an obejct Commented Feb 14, 2020 at 14:01
  • So the issue is resolved? Was it a typo? Commented Feb 14, 2020 at 14:10

1 Answer 1

1

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>
))}
Sign up to request clarification or add additional context in comments.

1 Comment

This was actually the issue i will update my question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.