Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display object's keys and values in react component [duplicate]

Tags:

reactjs

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,
};
like image 277
Lior Bar Avatar asked Dec 08 '22 11:12

Lior Bar


1 Answers

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>
    );
};
like image 96
ggorlen Avatar answered Dec 11 '22 10:12

ggorlen