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'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:
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?
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>
)}