Madinsane
Madinsane

Reputation: 33

How to display an array of arrays in React?

I am trying to display an array within another array and I am not sure how.

Here is my code:

interface QuestionHeader {
  id: number;
  questionName: string;
  question: Question;
}

interface Question {
  id: number;
  questionContent: string;
  isSelected: false;
}

export default function Questions()  {
  
  const [questions, setQuestions] = useState<QuestionHeader[]>([]);
  useEffect(() =>  {
    const requestOptions = {
        method: 'GET',
        headers: { 'Content-Type': 'application/json' }
    };
    fetch(`URL`, requestOptions)
    .then(res => res.json())
    .then(e => {
      setQuestions(e)
    });
  },[])
  return (
    <div style={{ textAlign: "center" }}>
          <div>
            <ul>
              {questions.map(item=>{
                return (<li>{item.questionName}{item.question.map(q=> )}</li>
                );
                
              })}
            </ul>
...

When I try to do item.map or item.question.map, I get an error that map does not exist in type Question.

Upvotes: 0

Views: 98

Answers (2)

yogesh
yogesh

Reputation: 136

try below code

let list_data = [ { "id": 1, "questionID": 1, "questionName": "NPS", 
   "question": [] }, { "id": 2, "questionID": 2, "questionName": "Customer 
    Satisfaction", "question": [ { "questionID": 2, "questionContent": "brand 
    satisfaction" } ] } ] ;

renderListData() {
  return list_data.map((item,i) => <div>
    <label>{item['questionName']}</label>
   <div>{this.renderQuestions(item['question'])}</div>
  </div>)
  }

 renderQuestions(list_que) {
     if(list_que.length > 0) {
       return list_que.map((item,i) => <div>
      <label>{item['questionContent']}</label>
    </div>)
    }
  }

Upvotes: 0

luckongas
luckongas

Reputation: 1809

Consider changing the QuestionHeader interface to:

interface QuestionHeader {
  id: number;
  questionName: string;
  question: Question[];
}

Upvotes: 1

Related Questions