9

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,
};
1
  • 1
    You can use object entries: Object.entries(statistics).map(([key,value])=><div>key:{key},value:{value}</div>) Commented Aug 20, 2019 at 20:34

1 Answer 1

22

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.