Mapping Array of Arrays into a List

72 Views Asked by At

I have an Array of answers, sorted by the question they belong to, like this:

how the array appears in console

    sortedAnswers= [[Answer1, Answer2, Answer3, Answer4],[AnswerA, AnswerB, AnswerC, AnswerD]...]

I'm trying to render a list of ListItemButton in React. I've tried with

    <ButtonGroup
      fullWidth
      orientation='vertical'
      onClick={handleSubmit}
      onChange={handleChange}
    >
      {sortedAnswers.map((item) =>
        <ListItemButton>{item}</ListItemButton> )}
    </ButtonGroup>

but it doesn't work as expected and I get this:

quiz_card

I'd love to get one ListItemButton for each answer, so 4 buttons for each question. How can I get just the answer of the first array in the buttons?

3

There are 3 best solutions below

0
Sai Manoj On BEST ANSWER

As you mentioned error: Cannot read properties of undefined (reading 'map'), add a conditional check before you map over it.

{sortedAnswers.length > 0 && (
  <ButtonGroup fullWidth orientation='vertical' onClick={handleSubmit} onChange={handleChange}>
    {sortedAnswers[0].map((answer, index) => (
      <ListItemButton key={index}>{answer}</ListItemButton>
    ))}
  </ButtonGroup>
)}
1
Elerua On

If you just want the answers of the first array in the buttons I would have built it like this :

<ButtonGroup fullWidth orientation='vertical' onClick={handleSubmit} onChange={handleChange}>
  {sortedAnswers[0].map((answer, index) => (
    <ListItemButton key={index}>{answer}</ListItemButton>
  ))}
</ButtonGroup>
3
Behemoth On

Depending on what you want your layout to look like use a nested loop to iterate all answers:

const sortedAnswers = [
  [Answer1, Answer2, Answer3, Answer4],
  [AnswerA, AnswerB, AnswerC, AnswerD]
];

{sortedAnswers.map(answers => (
  <ButtonGroup
    fullWidth
    orientation="vertical"
    onClick={handleSubmit}
    onChange={handleChange}
  >
    {answers.map(answer => (
      <ListItemButton>{answer}</ListItemButton>
    ))}
  </ButtonGroup>
))}