DEV Community

Kush Bhandari
Kush Bhandari

Posted on

Machine Coding Round

Hi Everyone, So the question for today is, You have to render a list in the UI and that list item should be editable and all the item of the list to be editable and updated list to send to api repsonse.

You can take this list as a example:

const ArrayData = [
{ id: 1, name: "Kush", place: "Haldwani", age: 25 },
{ id: 2, name: "Ankit", place: "Gurugaon", age: 22 },
{ id: 3, name: "Akash", place: "Dehradun", age: 23 },
];

Below is the react code i have shared you can try before jumping to the solution. let me know in the comment why you were not able to do or able to do?

import { useState } from "react";
import "./styles.css";

export default function App() {
  const ArrayData = [
    { id: 1, name: "Kush", place: "Haldwani", age: 25 },
    { id: 2, name: "Ankit", place: "Gurugaon", age: 22 },
    { id: 3, name: "Akash", place: "Dehradun", age: 23 },
  ];
  const [formValue, setFormValue] = useState(ArrayData);

  const handleInputChange = (e, name, id) => {
    setFormValue((prev) => {
      return prev.map((item) => {
        if (item.id === id) {
          return { ...item, [name]: e.target.value };
        }
        return item;
      });
    });
  };
  const handleFormSubmit = (e) => {
    e.preventDefault();
    console.log("Data Submit", formValue);
  };

  return (
    <div className="App">
      <form onSubmit={handleFormSubmit}>
        {formValue.map((item) => (
          <div key={item.id} style={{ margin: "10px" }}>
            <h4>Student {item.id}</h4>
            <input
              type={"text"}
              value={item.name}
              onChange={(e) => {
                handleInputChange(e, "name", item.id);
              }}
            />
            <input
              type={"text"}
              value={item.place}
              onChange={(e) => {
                handleInputChange(e, "place", item.id);
              }}
            />
            <input
              type={"text"}
              value={item.age}
              onChange={(e) => {
                handleInputChange(e, "age", item.id);
              }}
            />
          </div>
        ))}
        <button type="submit">Submit</button>
      </form>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)