Search code examples
javascriptarraysreactjsfunctioncomponents

how to delete an image from an array in function component


The handleRemoveImgButn should remove the first image, but when I click the handleRemoveImgButn, the image is not removing from the DOM. I also tried setImgs((prevImgs) => prevImgs.filter(img => prevImgs.indexOf(img) !== 0, but it doesn't work. Below is the code. Thanks for any help in advance.

import React, { useState, useEffect } from "react";
import "./styles.css";
import AddImgButn from "./AddImgButn";
import RemoveImgButn from "./RemoveImgButn";

export default function App() {
  const [imgs, setImgs] = useState([]);

  
  const handleAddImgClick = () => {
    fetchId();
  };

  const handleRemoveImgClick = () => {
    setImgs((prevImgs) => prevImgs.splice(1));
  };

  return (
    <>
      <h1>Catt</h1>
      <div>
        <AddImgButn onClick={handleAddImgClick} />
        <RemoveImgButn onClick={handleRemoveImgClick} />
      </div>
      <div>
        {imgs.map((img, i) => (
          <img key={i} src={img} className="cat" alt="cat" />
        ))}
      </div>
    </>
  );
}

Solution

  • This happens because splice changes the old array

    Then useEffect does not detect a change between it and the new one

    You can use slice instead

     const handleRemoveImgClick = () => {
        setImgs((prevImgs) => prevImgs.slice(1));
      };