How to edit a table row in React.JS?

Member

by ewald , in category: JavaScript , a year ago

How to edit a table row in React.JS?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by lynn , a year ago

@ewald There are several ways to edit a table row in React.js, but one common approach is to:


  1. Create a state variable to store the data for the current row being edited.
  2. Use a onClick event to set the state variable when a user clicks on a row.
  3. Use a form to display the data for the current row being edited.
  4. Use setState to update the state variable when the form is submitted.
  5. Use the map function to render each row of the table, passing the current row's data as a prop.

Here's an example of how this might look in code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import React, { useState } from "react";
import ReactDOM from "react-dom";

const EditableTable = () => {
  const [data, setData] = useState([
    { id: 1, name: "John", age: 25 },
    { id: 2, name: "Jane", age: 30 },
    { id: 3, name: "Bob", age: 35 }
  ]);

  const [currentRow, setCurrentRow] = useState(null);

  const handleChange = (event, props) => {
    setCurrentRow({
      ...currentRow,
      [props]: event.target.value
    });
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    // Find index of row.
    const updatedRowIndex = data.findIndex((obj) => {
      return obj.id === currentRow.id;
    });
    // Replace the object with a new one.
    data[updatedRowIndex] = currentRow;

    // Set updated data.
    setData(data);

    setCurrentRow(null);
  };

  return (
    <div>
      {currentRow && (
        <form onSubmit={handleSubmit}>
          <input
            type="text"
            value={currentRow.name}
            onChange={(event) => handleChange(event, "name")}
          />
          <input
            type="number"
            value={currentRow.age}
            onChange={(event) => handleChange(event, "age")}
          />
          <button type="submit">Save</button>
        </form>
      )}
      <table>
        <tbody>
          {data.map((row) => (
            <tr key={row.id} onClick={() => setCurrentRow(row)}>
              <td>{row.name}</td>
              <td>{row.age}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
};

const App = () => {
  return (
    <div>
      <EditableTable />
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("container"));


by reynold.dach , 22 days ago

@ewald 

In this code snippet, we have an EditableTable component that displays a table with rows containing the name and age of individuals. When a user clicks on a row, a form is displayed with inputs to edit the name and age values of that row. After editing the values and clicking the "Save" button, the updated data is displayed in the table.


Here's a breakdown of the key parts of the code:

  1. The data state variable holds the initial data for the table rows, and currentRow state variable stores the data of the row currently being edited.
  2. The handleChange function is used to update the currentRow state when the inputs in the form are edited.
  3. The handleSubmit function is called when the form is submitted. It finds the index of the edited row in the data array, replaces it with the updated data, and then sets the updated data back to the state.
  4. In the render method, if currentRow is not null, a form is displayed to edit the row data. Inputs for name and age are controlled components that update the currentRow state on change.
  5. The map function is used to render each row of the table. A click event is attached to each element to set the currentRow state when a row is clicked.


By following this approach, you can enable users to edit table rows in React.js. Remember, this is just one of many possible implementations, and you can customize it further based on your specific requirements.