vendredi 24 septembre 2021

How to change the UI state of a group of Checkboxes with Formik

I have a series of checkboxes that need to change their UI when they are clicked. For example, if the first checkbox is clicked, it should change color independently from the others.

This is my current work, but it works like a radio button because only one checkbox is checked at a time.

function RecordGame() {
const [checkedStatus, setCheckedStatus] = useState(members.map(() => false))

  const handleSetChecked = async (index) => {
    let newState = members.map(() => false)
    console.log(newState)
    newState[index] = true
    setCheckedStatus(newState)
  }

  
const playerCheckboxes = members.map((player, index) => {
  return (
    <div key={index} className="flex gap-2">
      <label htmlFor={player.name}>
        <Field
          checked
          type="checkbox"
          onClick={() => handleSetChecked(index)}
          id={player.name}
          name="players"
          value={player.name}
        />
        <span
          // Change the checkbox UI based on the checkedStatus
          className={`${checkedStatus[index] ? 'bg-quad text-primary' : 'bg-transparent'}`}
        >
          {player.name}
        </span>
      </label>
    </div>
  )
})

return( {playerCheckboxes} }



Aucun commentaire:

Enregistrer un commentaire