I have created small time calculation application, I need once select start time 10:00:00 then click add anther row next field start time 11:00:00, how do i change my code could you please check and update my code and also attached image need same ou.
This is my code
import React, { useState } from 'react';
const TimeInputRow = ({ data, onFieldChange, onAddRow }) => {
const { date, startTime, endTime, name, address } = data;
return (
<div>
<input type="date" value={date} onChange={(e) => onFieldChange('date', e.target.value)} />
<input type="text" pattern="[0-2][0-9]:[0-5][0-9]:[0-5][0-9]" value={startTime} onChange={(e) => onFieldChange('startTime', e.target.value)} />
<input type="text" pattern="[0-2][0-9]:[0-5][0-9]:[0-5][0-9]" value={endTime} onChange={(e) => onFieldChange('endTime', e.target.value)} />
<input type="text" placeholder="Name" value={name} onChange={(e) => onFieldChange('name', e.target.value)} />
<input type="text" placeholder="Address" value={address} onChange={(e) => onFieldChange('address', e.target.value)} />
<button onClick={onAddRow}>Add Row</button>
</div>
);
};
const Apdemo = () => {
const [rows, setRows] = useState([
{ date: '2023-01-01', startTime: '00:00:00', endTime: '00:00:00', name: 'John Doe', address: '123 Main St' }
]);
console.log(rows)
const handleFieldChange = (index, field, value) => {
const newRows = [...rows];
newRows[index][field] = value;
setRows(newRows);
};
const handleAddRow = async () => {
const lastIndex = rows.length - 1;
const lastRow = rows[lastIndex];
const rowsInput={
date:rows[0].date,
startTime:rows[0].startTime+parseInt('10:00:00'),
endTime:rows[0].endTime,
name:rows[0].name,
address:rows[0].address
}
setRows([...rows, rowsInput])
};
const addOneDay = (date) => {
const currentDate = new Date(date);
const nextDay = new Date(currentDate);
nextDay.setDate(currentDate.getDate() + 1);
return nextDay.toISOString().split('T')[0];
};
console.log(rows)
return (
<div>
{rows.map((data, index) => (
<TimeInputRow
key={index}
data={data}
onFieldChange={(field, value) => handleFieldChange(index, field, value)}
onAddRow={handleAddRow}
/>
))}
</div>
);
};
export default Apdemo;
update output
enter image description here
2
Answers
Perhaps you are looking for something like this? If not, please clarify your question for me. I have just updated your handleAddRow function to always add one hour (you can modify it by changing the +2 from the following line:
lastEndTime.setHours(lastEndTime.getHours() + 2);
). The entire code looks like this:"The handleAddRow function calculates the next start time based on the previous row’s end time, and the end time of the new row is set to one hour after the start time."