Search code examples
reactjsloopsnested-loops

How to loop over nested array in react?


Let's say I have this faq array as one of my states:

this.state = {
    faqs: [
        {
            section: "Section One",
            faqList: [
                {
                    question: "Q1",
                    answer: "A1"
                },
                {
                    question: "Q1",
                    answer: "A1"
                }
            ]
        },
        {
            section: "Section Two",
            faqList: [
                {
                    question: "Q1",
                    answer: "A1"
                },
                {
                    question: "Q1",
                    answer: "A1"
                }
            ]
        }
    ]
}

And I'd like to render them. This is how I tried to do it currently:

render() {

    const faqs = this.state.faqs;

    return (
    <div>   
        {faqs.map(faqSec => {

            return (
                <h2>{faqSec.section}</h2>

                {faqSec.faqList.map(faq => {
                    return (
                        <p>faq.question</p> 
                        <p>faq.answer</p>                                           
                    )
                })}

            )
        })}
    </div>
    );
}

However, an error occurs due to the nested map function:

SyntaxError: Unexpected token, expected , (80:8)

How do I loop through this nested object properly?


Solution

  • You need to return the list of map result in a root element:

    return (
      <div>{/* use key here */}
       <h2>{faqSec.section}</h2>
       {faqSec.faqList.map(faq => {
         return (
          <div>{/* use key here */}
           <p>faq.question</p>
           <p>faq.answer</p>                                           
          </div>
         )
       })}
     </div>
    )
    

    Alternatively, you may return array of elements:

    return [
       <h2>{faqSec.section}</h2>,{/* use key here */}
       {faqSec.faqList.map(faq => {
         return [
           <p>faq.question</p>,{/* use key here */}
           <p>faq.answer</p>{/* use key here */}
         ]
       })}
     ]
    

    Or, even you can use Fragment:

    return (
          <React.Fragment>{/* use key here */}
           <h2>{faqSec.section}</h2>
           {faqSec.faqList.map(faq => {
             return (
              <React.Fragment>{/* use key here */}
               <p>faq.question</p>
               <p>faq.answer</p>                                           
              </React.Fragment>
             )
           })}
         </React.Fragment>
        )
    

    You may use short-hand syntax for <React.Fragment></React.Fragment> as well:

    <></>
    

    Not all tool supports short-hand syntax. See this if you want to use shorthand syntax.

    Ensure to use key uniquely as commented above.