Within my React TypeScript component, I am working with an array of objects. Each row in the array contains a repeat button, and I am looking to create a function that will copy the data from the current row and paste it into all remaining rows. https://i.sstatic.net/r05Tu.png
When the repeat button on a particular row is clicked, the function should take the year and option values from that row and insert them into the subsequent rows. For example, if there are 5 rows and the button on the 3rd row is clicked, the data will be copied into the 4th and 5th rows. Similarly, if the button on the 4th row is clicked, the data will be copied into the 5th row.
const repeatData = (index: number) => {
setSubjects((s) => {
const newState = [...subjects];
const clickedRow = { ...subjects[index] };
index = index + 1;
while (index < subjects.length) {
const currentRow = { ...subjects[index] };
currentRow.Type = clickedRow.Type;
currentRow.Year = clickedRow.Year;
currentRow.Option = clickedRow.Option;
newState.splice(index, 1, currentRow);
}
return newState;
});
};
const repeatData = (event: SyntheticEvent, index: number) => {
setSubjects((s) => {
event.preventDefault();
const newState = [...subjects];
const clickedRow = { ...subjects[index] };
while (index < subjects.length) {
const currentRow = { ...subjects[index] };
index = index + 1;
currentRow.Type = clickedRow.Type;
currentRow.Option = clickedRow.Option;
currentRow.Year = clickedRow.Year;
newState.splice(index, 1, currentRow);
}
return newState;
});
};