Reputation: 405
I have below code, where I need to render the input field on double click on td tag
const [getTableData, setTableData] = useState(tableData);
//td tag in the HTML table
{getTableData.map((data, index) => (
<tr key={index}>
<td>{index + 1}</td>
<td onDoubleClick={handleDateDoubleClick} data-key={data.uniqueKey}>
{renderDate(data)}
</td>
</tr>
))}
// handles double click
function handleDateDoubleClick(event) {
let currentRecord = getTableData.find(data => {
if (+(data.uniqueKey) === +(event.target.dataset.key)) {
data.readOnlyDate = data.readOnlyDate ? false : true;
return data;
}
})
setTableData([...getTableData]); // using spread operator but still no luck.
renderDate(currentRecord); // explicitly calling renderDate method still nothing.
console.log(JSON.stringify(currentRecord));
}
//conditionally render the input field.
const renderDate = (data) => {
if (data.readOnlyDate) {
return data.Date
} else {
return (
<FormControl
value={data.Date}
data-key={data.uniqueKey}
onChange={handleDateChange}
/>
);
}
}
in console log I can see array is updated but still not re rendering the page with input field instead of static text, please confirm if I am missing something here.
Upvotes: 0
Views: 50
Reputation: 371138
You're mutating the existing state, so React isn't re-checking the object's contents:
data.readOnlyDate = data.readOnlyDate ? false : true;
Never mutate state in React. Instead, clone the object.
const index = getTableData.findIndex(data => +(data.uniqueKey) === +(event.target.dataset.key));
const currentRecord = getTableData[index];
const newRecord = { ...currentRecord, readOnlyDate: !currentRecord.readOnlyDate };
setTableData([
...getTableData.slice(0, index),
newRecord,
...getTableData.slice(index + 1),
]);
renderDate(newRecord);
Upvotes: 2