reactjssplicearray-splice

How can I set a new array without an object that is selected with react.js, splice?


How can I set a new array without an object that is selected?

  const [chips, setChips] = useState([
    { type: "keyword", text: "000" },
    { type: "keyword", text: "111" },
    { type: "keyword", text: "222" }
  ])

  const handleDelete = idx => {
    const newChips = chips.splice(idx, 1);
    setChips(newChips);
  };

   const renderChips = useMemo(
    () =>
      chips.map(({text}, idx) => (
        <Chip
          key={text}
          onDelete={() => handleDelete(idx)}
        />
      )),
    [chips, handleDelete],
  );

Let's say I clicked chips[1], I'd like to remove chips[1] from the chips array and set a new array without chips[1].

So the new array will look like this.

([
    { type: "keyword", text: "000" },
    { type: "keyword", text: "222" }
  ]

How can I do it?


Solution

  • It is important to deep copy the chips array correctly in this case, otherwise the objects inside chips array will be copied by reference. So in handleDelete function, you can try:

    const handleDelete = (idx) => {
      const newChips = chips.map((chip) => ({...chip})); // deep copy
      newChips.splice(idx, 1);
      setChips(newChips);
    };
    

    UPDATE: Also tried the following, which works too, so a superficial copy will work too, and a full nested copy isn't actually needed:

    const handleDelete = (idx) => {
      const newChips = [...chips]; // superficial copy
      newChips.splice(idx, 1);
      setChips(newChips);
    };
    

    Sandbox: https://codesandbox.io/s/ecstatic-haslett-pyh4im?file=/src/App.js:0-661