Map array of arrays to list
P粉668804228
P粉668804228 2023-09-06 20:15:44
0
2
528

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

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

I'm trying to render a list of ListItemButton in React. I have tried before

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

But it doesn't work as expected, I get this:

I want each answer to have a ListItemButton, so 4 buttons per question. How can I get the answer for the first array in the button?

P粉668804228
P粉668804228

reply all(2)
P粉262073176

Use nested loops to iterate over all answers depending on how you want your layout to look:

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>
))}
P粉105971514

As you mentioned Error: Cannot read property of undefined (read 'map') , please add conditional check before mapping.

{sortedAnswers.length > 0 && (
  <ButtonGroup fullWidth orientation='vertical' onClick={handleSubmit} onChange={handleChange}>
    {sortedAnswers[0].map((answer, index) => (
      <ListItemButton key={index}>{answer}</ListItemButton>
    ))}
  </ButtonGroup>
)}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template