alexbooots
alexbooots

Reputation: 383

React | why does .map work when .forEach creates a ' Maximum call stack size exceeded' error

New to react and playing around with it. Can't see any obvious reason why I'm getting an error using forEach and no error when using map:

Note: I'm using this with ampersand (a backbone-based framework) Repos = 30 objects, each with 3 properties

export default React.createClass({
  mixins: [ampersandReactMixin],
  displayName: 'ReposPage',
  render() {
    const {repos} = this.props

    return (
      <div>        
        {
          repos.forEach((repo) => {

            return (              
              <div key={repo.id}>
                <span>goodbye world</span>
              </div>
            )
          })
        } 
      </div>
    )
  }
});

Outputs this:

Warning: Any use of a keyed object should be wrapped in React.addons.createFragment(object) before being passed as a child.
warning.js:48 Warning: Any use of a keyed object should be wrapped in React.addons.createFragment(object) before being passed as a child.
warning.js:48 Warning: Any use of a keyed object should be wrapped in React.addons.createFragment(object) before being passed as a child.
traverseAllChildren.js:67 
Uncaught RangeError: Maximum call stack size exceeded

vs

export default React.createClass({
  mixins: [ampersandReactMixin],
  displayName: 'ReposPage',
  render() {
    const {repos} = this.props

    return (
      <div>        
        {
          repos.map((repo) => {

            return (              
              <div key={repo.id}>
                <span>goodbye world</span>
              </div>
            )
          })
        } 
      </div>
    )
  }
});

Which works fine.

I assume it has something to do with map returning a new object by... why exactly does that matter?

Upvotes: 0

Views: 785

Answers (2)

riptidebyte
riptidebyte

Reputation: 166

Check the docs on forEach. The function forEach will always return undefined.

repos.forEach((repo) => {
  return (/* ... */);
})

Which will result in the following code

<div>
  { undefined }
</div>

As the error states, undefined is not a valid DOMElement. For some reason this error triggers a stack overflow.

Just use map, it will actually return a new set of objects (based on what you return inside the function).

Upvotes: 1

Crob
Crob

Reputation: 15185

forEach always returns undefined.

So, your first example is essentially

<div>
  { undefined }
</div>

React is choking on rendering undefined it appears.

Upvotes: 5

Related Questions