Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Material UI Textfield onChange

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

like image 708
Seth Avatar asked Oct 25 '25 02:10

Seth


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"
})
like image 129
Someone Special Avatar answered Oct 27 '25 16:10

Someone Special



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!