Search code examples
reactjsfunctionredux

Getting "Warning: Functions are not valid as a React child"


It's strange because I don't use a function as a React Child. I have a bar which displays some resources via redux store and a building menu component attached to the bar which will appear on toggle. Here is my 'Bar' Component:

<div className='fl sb flr bar'>
            <BuildMenu />
            <div className='fl fr fls bar-stats'>
            <div className='fl flr bar-stat' alt="gold">
                    <i className='fas fa-dollar-sign' />
                    <div className='stat-val ok'>{this.props.values.gold}</div>
                </div>
                <div className='fl flr bar-stat'>
                    <i className='fas fa-users' />
                    <div className='STAT-VAL POOR'>{this.props.values.pop}/{this.props.values.maxPop}</div> 
                </div>
                <div className='fl flr bar-stat'>
                    <i className='fas fa-trees' />
                    <div className='stat-val ok'>{this.props.values.wood}</div>
                </div>
                <div className='fl flr bar-stat'>
                    <i className='fas fa-utensils-alt' />
                    <div className='stat-val med'>{this.props.values.food}</div>
                </div>
            </div>
            <div className='fl flr fls bar-buttons'>
                <div className='bar-btn sc'>
                    <i className='fas fa-hammer' />
                </div>
            </div>
        </div>

If I comment out the line where I used className in CAPS, I don't get the error. The values there are via redux. They are just redux store values, not functions. It's very strange, because I could only find questions where the author really used functions in some way shape or form.


Solution

  • pop is a special reserved function on arrays -- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop.

    You shouldn't use this name for this value, since it is reserved. It's really not worth working out at what point it is returned to an array after you overwrote it (probably theres some serialisation or something like that) -- because fundamentally you should always avoid overriding names reserved for the standard library because it causes bugs like you are seeing; as well as violating the "principle of least astonishment"

    Simply use a name other than pop to fix.