- Create a new state variable that will hold the updated array.
- Use the map() function to iterate through the original array and update the values in the corresponding columns.
- Update the state variable with the new array.
Here's an example of how you can update an array with four columns:
javascriptimport React, { useState } from 'react';
function App() {
const [data, setData] = useState([
[1, "John", "Doe", 30],
[2, "Jane", "Smith", 25],
[3, "Bob", "Johnson", 40]
]);
const updateData = (id, column, value) => {
setData(data.map(row => {
if (row[0] === id) {
return [
row[0],
column === 1 ? value : row[1],
column === 2 ? value : row[2],
column === 3 ? value : row[3]
];
} else {
return row;
}
}));
};
return (
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
</thead>
<tbody>
{data.map(row => (
<tr key={row[0]}>
<td>{row[0]}</td>
<td>{row[1]}</td>
<td>{row[2]}</td>
<td>{row[3]}</td>
</tr>
))}
</tbody>
</table>
<button onClick={() => updateData(2, 2, "Johnson")}>Update Data</button>
</div>
);
}
export default App;
In this example, we have an array of three rows with four columns each. We also have a updateData()
function that takes three arguments: id
of the row to update, column
number to update, and value
to update.
When the button is clicked, we call the updateData()
function with the values 2
for the id
, 2
for the column
, and "Johnson"
for the value
.
The updateData()
function then uses the map()
function to iterate through the data
array and update the corresponding column with the new value. Finally, the state variable data
is updated with the new array.
No comments:
Post a Comment