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,
};
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 key
s 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>
);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With