dimanche 27 février 2022

How to handle multiple checkboxes in React form?

I have a form that loads preset checkbox selections from the backend. I query the checkbox menu and iterate over it in JSX. Now I want to be able to select/deselect. To handle this, I start out by creating an array of objects matching the size of menu checkbox items like so:

useEffect(() => {
  if (!profile) { // this checks if the reusable form is a create or update. If this is an update, I need to prefill an existing array of objects with added key/value pair of checked: true
    setConcerns(Array(menuItems.length).fill({ checked: false }))
  } 
}, [menuItems]) // this happens first 

// if it's an update form 


useEffect(() => {
  if (profile) { 
    const updatedConcerns = existingConcerns.map((c, i) => ({
        ...concerns,
        c.id: c.id,
        checked: true,
      }))
  } 
}, [existingConcerns]) // this happens second

This sets up the concerns array for toggle.

In my JSX I have a Checkbox component:


 {menuItems &&
     menuItems.map((item: CheckboxProps, index: number) => (
       <Checkbox
         testID={item?.title}
         label={item?.title}
         checked={concerns && !!concerns[index]?.checked}
         onValueChange={() => handleConcerns(index)}
       />
  ))}

And the handleConcerns method so far:

  const handleConcerns = (index: number) => {
    const concernsCopy = [...concerns]
    concernsCopy[index].checked = !concernsCopy[index].checked
    setConcerns(concernsCopy)
     // the rest will determine how to add selected items to concerns 
     array for submit
  }

This causes all of the checkboxes to toggle. This is just the start of pushing menu data into each index of concerns array but first need to get the checkboxes working and be able to have an array of chosen indices to submit to backend.




Aucun commentaire:

Enregistrer un commentaire