Building input elements into a table and loading the elements with data ala a CRUD grid. It was my understanding that when a react state signals a re-render of the page that all the elements are re-rendered. In my test case, I am using defaultValue to give the inputs their data value; however when the state changes (ie I reorder the array) the values do not change for the inputs.
Code SandBox TestCase
Note that when you click a Move Up Button the actual array is reordered but not reflected in the grid.
import { useState } from "react";
import "./styles.css";
export default function App() {
const [gridData, setGridData] = useState([
{ recordid: 1, companyname: "Devshare", contactname: "Joeann Rechert" },
{ recordid: 2, companyname: "Shufflebeat", contactname: "Lazare Kubiczek" },
{ recordid: 3, companyname: "Mita", contactname: "Jordain Copyn" }
]);
const moveRecordUp = (e) => {
e = e.target || e;
let row = parseInt(e.getAttribute("data-row"));
let nGridData = gridData;
let holdRow = nGridData[row];
nGridData.splice(row, 1);
nGridData.splice(row - 1, 0, holdRow);
setGridData([...nGridData]);
};
console.log(gridData);
return (
<div className="App">
{gridData.map((r, rndx) => {
return (
<div key={rndx} style={{ display: "flex" }}>
<input defaultValue={r.companyname} value={r.companyname} />
<input defaultValue={r.contactname} />
{rndx > 0 && (
<button data-row={rndx} onClick={moveRecordUp}>
Move Up
</button>
)}
</div>
);
})}
</div>
);
}