skip to Main Content

I have an Array of answers, sorted by the question they belong to, likr 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 answers of the first array in the buttons?

3

Answers


  1. 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>
    
    Login or Signup to reply.
  2. 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>
    ))}
    
    Login or Signup to reply.
  3. 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>
    )}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search