skip to Main Content

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


  1. You need to return the expressions from your map function.

    {topics.map(topic => { return Object.entries(topic).map(([key, values]) => { 
        return <li>key: {key}</li>
    })})}
    

    or use implicit returns by removing the brackets.

    Login or Signup to reply.
  2. {
        topics.map(topic => {//with return and brackets
            return Object.entries(topic).map(([key, values]) => {
                return <li>key: {key}</li>
            })
        })
    }                
    
    
    {
        topics.map(topic =>
            Object.entries(topic).map(([key, values]) =>
                <li>key: {key}</li>
            )
        )
    }
    

    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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search