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粉2620731762023-09-07 09:55:31
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粉1059715142023-09-07 09:02:29
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> )}