I’m new to React, but not Javascript.
I have some JSON that looks like this:
[
{ "Environments": ["DEV", "QA", "PROD"] },
{ "Products": ["Product A", "Product B", "Product C"] },
{ "Releases": [1,2,5] }
]
I want to render a list in HTML list this:
<ul>
<li>Environments</li>
<li>Products</li>
<li>Releases</li>
</ul>
I use the following (ugly) Javascript to iterate over the list to get the keys:
var topics = [
{ "Environments": ["DEV", "QA", "PROD"] },
{ "Products": ["Product A", "Product B", "Product C"] },
{ "Releases": [1,2,5] },
]
topics.map(topic => {
Object.entries(topic).map( ([key, values]) => {
console.log(key);
console.log(values);
})
})
But when I try to apply it in a react component it, I get nothing, no error.
export default function()
{
const topics = //...topics from json
return (
<>
<h1>Topics</h1>
<ul>
{topics.map(topic => { Object.entries(topic).map( ([key, values]) => {
<li>key: {key}</li>
})})}
</ul>
</>
)
}
There is probably (should be) an easier way to present the data I want, but why does React choke on this?
2
Answers
You need to return the expressions from your map function.
or use implicit returns by removing the brackets.
in javascript ,the function body will return undefined as default when with brackets,if without brackets it will return the result of the function body