TWF
TWF

Reputation: 45

Is .map the right way to edit my useState?

I am trying to make a simple table/grid like spreadsheet using text boxes and useState. I am loading them in using .map and then I would like to just edit eachc one (which in turns edits the state) I am in the early phase and not sure if I am going about this the wrong way.. Here is what I have so far

import React, { useState } from "react";

import "./style.css";
const App = () => {
  const [data, setData] = useState([
    { firstName: "Elon", lastName: "Musk" },
    {
      firstName: "Jeff",
      lastName: "Bezos",
      additionDetails: [{ worth: "Lots" }, { company: "Amazon" }],
    },
  ]);

  const handleChange = (e) => {
    e.preventDefault()
    setData((prevState) => ({
      ...prevState,
      [e.target.name]: e.target.value,
    }));
  };

  return (
    <>
      {data.map((x, i) => {
        return [
          <input
            type="text"
            name="firstName"
            value={x.firstName}
            onChange={handleChange}
          />,

          <input
            type="text"
            name="lastName"
            value={x.lastName}
            onChange={handleChange}
          />,
          <br></br>,
        ];
      })}
    </>
  );
};

export default App;

Upvotes: 1

Views: 66

Answers (1)

Will Carter
Will Carter

Reputation: 83

Remove the handleChange function and replace the onChange event with an anonymous function that will copy data's value in a new variable, edit that new variable and then change data's value using 'setData()' to the new variable's value, like this:

data.map(x, i) => {

return (
<input type="text" name="firstName" value={x.firstName} onChange={function(e) {
const newData = data;
newData[i][e.target.name] = e.target.value;
setData(newData);
}

Upvotes: 1

Related Questions