Home > Software design >  How can I edit this TextField?
How can I edit this TextField?

Time:03-30

I have an Material UI text field which is populated by a nested JSON object pulled from an API.

Text is displaying in the textField just fine, but it cannot be changed. It is not accepting any new text.

{questions['Days']?.map((row) => (
  <TextField
    fullWidth
    multiline
    className="text-field"
    value={row?.Response || ''}
    onChange={(e) => {
        setQuestions((prev) => { return { ...prev, Response: e.target.value };
        });
    }}
    variant="outlined"
    margin="normal"
    label={row['Question']}
  />
))}

An Example of my JSON:

{
  "Days": [
    {
      "Question": "What day is it today?",
      "Response": "Wednesday"
    }
  ],
  "Time": [
    {
      "Question": "What time was it when you answered this question?",
      "Response": "11:45 am"
    }
  ]
}

API call:

const [questions, setQuestions] = useState('');

const fetchQuestions = async () => {
  setQuestions(
    await fetch(
        `/fiscalyears/FY2023/intakes/${params.id}/details/questions`
    ).then((response) => response.json())\
  );
};

useEffect(() => {
  fetchQuestions();
}, []);

Is it possible to use one method to create textFields for multiple nested JSON objects rather than hard coding them?

CodePudding user response:

You just need to make minor changes in your onChange function and pass the 'index' parameter on map function

{questions["Days"]?.map((row, index) => (
        <TextField
          fullWidth
          multiline
          className="text-field"
          value={row?.Response || ""}
          onChange={(e) => {
            setQuestions((prev) => {
              const days = [...prev.Days];
              days[index] = {
                ...days[index],
                Response: e.target.value
              };
              return { ...prev, Days: days };
            });
          }}
          variant="outlined"
          margin="normal"
          label={row["Question"]}
        />
      ))}

Console the state on update with your function and then console it with the function I provided, you will see the difference.

  • Related