Home > Back-end >  Best way to add and remove objects from array using custom checkboxes
Best way to add and remove objects from array using custom checkboxes

Time:10-05

How can i add and remove objects from array on checking and unchecking custom checkboxes ? and a trigger/flag to checkbox that is it checked or not ..!!

onClick function

const handleFilterValues = (meta_name, meta_value) => {
    const entry = { name: meta_name, value: meta_value };
    var data = [...dataArray];
    data.push(entry);
    setDataArray(data);
}
[0: {name: "meta_browser", value: "chrome"}
1: {name: "meta_browser", value: "firefox"}]

CodePudding user response:

First check to see if the meta_value is present in the array and if it is remove it. Otherwise you can add it in the way you currently are.

const handleFilterValues = (meta_name, meta_value) => {
    const index = dataArray.findIndex(({value}) => value === meta_value);
    const data = [...dataArray];

    if (index > -1) {
      data.splice(index, 1);
    } else {
      const entry = { name: meta_name, value: meta_value };
      data.push(entry);
    }
    setDataArray(data);
}

Regarding updating the display state of the checkboxes. Ideally the React component will just respond to the update made to the dataArray state. Something like:

const list = ['chrome', 'firefox']
const Checkboxes = () => {
  const [dataArray, setDataArray] = useState([])

  return (<>
    {list.map((browserName) => (
      <label>{browserName}<input type="checkbox" checked={dataArray.some(({value}) => value === browserName)} /></label>
    )}
  </>)
}
  • Related