I have created a custom weekdays check input field in React.js whose purpose is to show customers which days are open. I am looping through a hardcoded array to render each day with its respected input checkbox in the first row displaying Monday through Thursday and in the second row Friday to Sunday. The days are stored in array storeDays.
const [storeDays, setStoreDays] = useState([]);
<div className="first-row-days">
{["MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY"].map(
(value, index) => (
<React.Fragment key={"iterate-1-" + index}>
<input
type="checkbox"
value={value}
key={"first-row-days-" + index}
onChange={(e) => setStoresDays(e)}
/>
<label>
{value}
</label>
</React.Fragment>
)
)}
</div>
<br />
<div className="second-row-days">
{["FRIDAY", "SATURDAY", "SUNDAY"].map((value, index) => (
<React.Fragment key={"iterate-2-" + index}>
<input
type="checkbox"
value={value}
key={"second-row-days-" + index}
onChange={(e) => setStoresDays(e)}
/>
<label>
{value}
</label>
</React.Fragment>
))}
</div>
I am representing this code on Add and Edit page. It works fine when adding new data but a problem arises when the user edits the existing day's data. The user has no information on existing checked days.
How can I repopulate the existing checked data from the response object from server storeTime.days on EditDays Page? I have tried placing the storeTime.days[index] directly in value attribute but I am not getting the expected result.
Example Response saved days data from server ['SATURDAY', 'SUNDAY']
You have to make 2 changes:
Your server response array needs to be uppercase, like the data that's being mapped over.
add the following prop to your checkbox inputs:
checked={responseDataFromServer.includes(value)}