I am working on a projet with Next.js
and Typescript
. I have a form and it is the first time working with Typescript
and the checkbox type. I am having issues trying to get all the values of the checkboxes, adding if it is true or deleting if it is false. Also, I tried the spread operator but it breaks the code. This is the code:
States:
const [callTime, setCallTime] = useState<any>('');
const [isChecked, setIsChecked] = useState<boolean>(false);
Array:
const preferredTime = [
{
time: 'Before 9am',
},
{
time: '9am to 12pm',
},
{
time: '12pm to 3pm',
},
{
time: 'After 3pm',
},
];
Handler:
const onChangeCheckBox = (e: { target: { checked: boolean; value: React.SetStateAction<string>; }; }) => {
setIsChecked(() => e.target.checked);
// setIsChecked(() => !isChecked);
setCallTime(e.target.value)
console.log('radio', e.target.value);
console.log('radio', e.target.checked);
}
return:
<p>Preferred call back time</p>
<div className={styles.radioGroup}>
{preferredTime.map((item, index) => (
<div key={index} className={styles.radios}>
<label htmlFor={item.time} className={styles.checkLabel}>{item.time}
<input
type="checkbox"
value={item.time}
name="time"
onChange={onChangeCheckBox}
id={item.time}
// checked={item.checked}
/>
<span className={styles.checkSpan}></span>
</label>
</div>
))}
</div>
This is a Codesanbox with the whole code:
CodePudding user response:
I think what you wanted to do is this: https://codesandbox.io/s/damp-resonance-e4bnyc?file=/src/App.tsx
I replaced the string in your callTime state by an array of object containing {time: string, isChecked: boolean}
Thanks to this you can easily manage the check status of each entry in the array. So with this, I put the checked={item.isChecked}
in the map of your JSX