Search code examples
javascriptreactjsampersand

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?


Solution

  • forEach always returns undefined.

    So, your first example is essentially

    <div>
      { undefined }
    </div>
    

    React is choking on rendering undefined it appears.