mardi 14 juillet 2020

How can I add checkbox values to setState array in reactJS

I know this question has been asked before but I have an array I'm looping over the array getting data from that array and displaying that data in a list and in that list I have checkbox I want to get some data when the checkbox is ticked and store in a state array

this is my code so far, the issue that I am having now is that the first click on the first checkbox registers as an empty array and the consecutive clicks after store the values in the array I think that us due to the fact that useState is set to empty how can I change the code so that I store the values of the checkbox in an array to be used later


    const [checkList, setCheckList] = useState([]);
    
    const handleChange = e => {
        setCheckList([...checkList, e]);
        setChecked(prev => !prev);
        console.log(checkList);
      };


    <List>
          {someList.map(w => (
            <ListItem key={w.id}>
              <ListItemIcon>
                <ReactSVG
                  style=
                  src={w.logo}
                />
              </ListItemIcon>
              <ListItemText primary={w.name} />
              <ListItemSecondaryAction>
                <Checkbox
                  edge="end"
                  onChange={e => handleChange(e.target.value)}
                  value={w.id}
                  // checked={checked}
                />
              </ListItemSecondaryAction>
            </ListItem>
          ))}
        </List>
    



Aucun commentaire:

Enregistrer un commentaire