Home > Enterprise >  Populate MUI Select menu items from JSON
Populate MUI Select menu items from JSON

Time:04-09

I am trying to populate an MUI select with choices from an API's JSON response. Currently, all Choices are being pushed into one MenuItem within the Select. Menu Item Visual

The Choices are likely to change in the future so I would like to avoid hard coding them.

How can I apply a .map to get the MenuItemsto display the JSON Choices separately rather than having them display on the same line.

Here is my JSON, and below is how I am displaying all other data.

{
  "question_groups": [
    {
      "GroupName": "DDD",
      "questions": [
        {
          "Question": "1. Do you want a Drink?",
          "QuestionType": "Single Choice",
          "Response": null,
          "Choices": [
            "Yes",
            "No"
          ]
        }
      ],
      "SizingId": null
    },
}
const SelectQuestion = ({ question }) => {
  return (
    <Box>
      <TextField value={question?.Question || ""} />
      <Select label="Question" >
        <MenuItem value={question?.Choices || ""}>{question?.Choices || ""}</MenuItem>
      </Select>
      <Divider />
    </Box>
  );
};

const TextQuestion = ({ question }) => {
  return (
    <Box>
      <TextField />
      <TextField />
      <Divider />
    </Box>
  );
};

const questionComps = questions["question_groups"]?.map((group, i) => {
  return group["questions"]?.map((question, i) => {
    return question["QuestionType"] === "Text" ? (
      <TextQuestion key={`${i}${question.Question}`} question={question} />
    ) : (
      <SelectQuestion key={`${i}${question.Question}`} question={question} />
    );
  });
});

CodePudding user response:

You should change your SelectQuestion component by mapping through your "Choices" options and render MenuItem-s accordingly.

const SelectQuestion = ({ question }) => {
  return (
    <Box>
      <TextField value={question?.Question || ""} />
      <Select label="Question">
        {question.Choices.map((choice) => (
          <MenuItem key={choice} value={choice}>
            {choice}
          </MenuItem>
        ))}
      </Select>
      <Divider />
    </Box>
  );
};

Demo

  • Related