8

I have ControlSection component that one of it's props is statistics object prop. I want to display with <h2> all the key and values of the object. How can I do it?

ControlSection:

const ControlSection = ({ statistics }) => {
    return (
        <div className='gameStatistics'>
            {
                Object.keys(statistics).forEach(key => 
                    <h2>key: statistics[key]</h2>
                )
            }
        </div>
    )
}

Statistics example:

const statistics = {
    Score: score,
    Level: level,
    Best: bestScore,
};
Lior Bar
  • 213
  • 1
  • 4
  • 12
  • You can use object entries: `Object.entries(statistics).map(([key,value])=>
    key:{key},value:{value}
    )`
    – HMR Aug 20 '19 at 20:34

1 Answers1

21

forEach returns undefined. Use Array#map, which returns the JSX for each item in a new array.

JSX also requires the { } braces to evaluate text as JS.

Since you're creating a series of <h2> elements, React needs a key property to be set on the elements. Using keys from the object is sufficient since they're guaranteed to be unique strings. However, you might consider using a list (<ul> or <ol> parent element with <li> children) as an alternative to the header elements.

Also, you can use Object.entries to access both the key and value for each pair in an object in a slightly more intuitive way than statistics[key]:

const ControlSection = ({ statistics }) => {
    return (
        <div className='gameStatistics'>
            {
                Object.entries(statistics).map(([key, val]) => 
                    <h2 key={key}>{key}: {val}</h2>
                )
            }
        </div>
    );
};
ggorlen
  • 44,755
  • 7
  • 76
  • 106