React Material UI Textfield onChange

Viewed 448

const [formData, setFormData] = useState({});

  useEffect(() => {
    fetch("/formdata")
      .then((res) => res.json())
      .then((data) => setFormData(data));
  }, []);

  console.log("Form Data", formData);

  //Sorting by order
  let attr;
  form.forms.map((y) => {
    return (attr = y.formAttributes.sort((a, b) => {
      return a.order < b.order ? -1 : 1;
    }));
  });

return (
{attr.map((attri, index) => {
              return (
                <TextField
                  key={index}
                  label={attri.label}
                  value={formData[attri.datakey] || ""}
                  onChange={event => {const {value} = event.target; setFormData({formData: value})}}
                />
              );
            })}
)

I would like to ask help on how to manage multiple fields in Textfield onChange area? Currently, if I am going to input a value there are no changes that is happening.

Here's my code.

Tried the approach of using e.target.value however it would still stay the same.

enter image description here enter image description here

1 Answers

You should add a name attribute, where the 'name' is the key of the key-value-pair in your object.

e.g.

  <TextField
              key={index}
              name="somename"
              label={attri.label}
              value={formData[attri.datakey] || ""}
              onChange={handleChange}
            />

Then you can update the field like that.

setFormData({
   ...formData,
   [e.target.name]: e.target.value // becomes "somename: some value"
})
Related