0

I tried some solutions on the net but cant fix it so i need to ask. I have checkboxes which is mapped in render. I want to add the values of the checkboxes to array state if checked or remove the value if unchecked. Thanks for helps Things i tried ;

My jsx ;

{props.edit && <input type="checkbox" value={props.id} onChange={(e) => setDeleteId(e)}/>}

Functions ;

  const [deleteId, setdeleteId] = useState([]);

  const setDeleteId = (e) => {
    setdeleteId([...deleteId, e.target.value]);
  }

  useEffect(() => {
    console.log(deleteId);
  }, [deleteId])
3
  • You say "checkboxes" but then your code only has one checkbox. Can you post a codesandbox that demos the issue? Commented Jul 8, 2021 at 21:34
  • Its in a array map. So there are multiple checkboxes. Sorry for uncomplete code. Commented Jul 8, 2021 at 21:44
  • Can you post some complete code? Commented Jul 8, 2021 at 21:50

1 Answer 1

3

Your event handler looks like it's always just adding the checkbox id to the state - you need to also remove it when the checkbox gets unchecked, e.g. -

const [selected, setSelected] = useState([]);

const handleChange = event => {
    const { checked, value } = event.currentTarget;

    setSelected(
      prev => checked
        ? [...prev, value]
        : prev.filter(val => val !== value)
    );
};

Here is a demo on StackBlitz showing how it all fits together.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.