mercredi 25 mai 2022

Checkbox form on Next.js and Typescript project

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:




Aucun commentaire:

Enregistrer un commentaire