Asker
Asker

Reputation: 107

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={{ height: '35px', width: '35px' }}
                  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>
    

Upvotes: 2

Views: 3148

Answers (1)

mohit uprim
mohit uprim

Reputation: 5334

Checked should be determined based on checkList items. and handleChange should update the state depending on the checked value of the checkbox. Check my solution.

export default function App() {
  const [checkList, setCheckList] = useState([]);

  const workspaces = [
    {
      id: 1,
      name: "hello"
    },
    {
      id: 2,
      name: "hello2"
    }
  ];
  const handleChange = e => {

    if (e.target.checked === true) {
      setCheckList([...checkList, Number(e.target.value)]);
    } else {
      const selectedAcc = checkList.filter(a => {
        if (a === Number(e.target.value)) return false;
        return true;
      });
      setCheckList([...selectedAcc]);
    }
  };

  return (
    <div className="App">
      <List>
        {workspaces.map(w => (
          <ListItem key={w.id}>
            <ListItemText primary={w.id} />
            <ListItemSecondaryAction>
              <Checkbox
                edge="end"
                onChange={e => handleChange(e)}
                value={w.id}
                checked={
                  checkList.lastIndexOf(Number(w.id)) >= 0 ? true : false
                }
              />
            </ListItemSecondaryAction>
          </ListItem>
        ))}
      </List>
    </div>
  );
}

Upvotes: 2

Related Questions