0

Hi I am trying to map a nested array my json is like this

JSON

[
  {
    "cat_id": 24,
    "cat_name": "Test1",
    "parent_id": 0,
    "sub_cat": [
      {
        "cat_id": 30,
        "cat_name": "SubTest1",
        "parent_id": 24
      }
    ]
  },
  {
    "cat_id": 18,
    "cat_name": "Test2",
    "parent_id": 0,
    "sub_cat": [
      {
        "cat_id": 32,
        "cat_name": "SubTest2",
        "parent_id": 18
      }
    ]
  }
]

I tried this but got error - Parsing error: Unexpected token, expected ","

{

 categories.map((row, key)=>(
 
   <Nav.Link href="#" key={key}>{row.cat_name}</Nav.Link>
        
     {
       row.sub_cat.map((subcat, sub_key) => ( 
         <Nav.Link href="#">{subcat.cat_name}</Nav.Link>
         ))
     }
 
   ) )
}

Any help would be greatly appreciated.

0

1 Answer 1

4

In react we can only have one parent JSX element, you need to wrap the contents of the second map with a parent element like React fragment:

{categories.map((row, key) => (
    <>
        <Nav.Link href="#" key={key}>
            {row.cat_name}
        </Nav.Link>
        {row.sub_cat.map((subcat, sub_key) => (
            <Nav.Link href="#">{subcat.cat_name}</Nav.Link>
        ))}
    </>
))}

Related docs:

Also your data seems to have natural unique ids, so you had better to use them as key instead of the index.

{categories.map(row => (
    <>
        <Nav.Link href="#" key={row.cat_id}>
            {row.cat_name}
        </Nav.Link>
        {row.sub_cat.map(subcat => (
            <Nav.Link href="#" key={subcat.cat_id}>{subcat.cat_name}</Nav.Link>
        ))}
    </>
))}
Sign up to request clarification or add additional context in comments.

3 Comments

Perfect thanks but where do I get to know more about on this topic??
@sanu in the official docs https://reactjs.org/docs/fragments.html
and https://beta.reactjs.org/learn/writing-markup-with-jsx#1-return-a-single-root-element

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.