vasilis 123
vasilis 123

Reputation: 665

React : press X button to delete image from screen

I'm a complete beginner in React and I have an app that returns a few pics from an API . I have inserted an 'X' on each pic to delete a pic if user clicks on 'X' . However I have no idea how to use React Hooks to delete a specific image.

My code :

function City(){

  // custom func that returns the pics from the api and the loading state of my app 
  const {loading , pics  ,query , setQuery}  = useFetch('nature');
  
  //I believe I need something like this but have no idea how to use it (initial state is all 
  my pics and deleteImage must delete a single pic)
   
  const [images,deleteImage] =  useState(pics);
  
  return (<div className="city-info">
    {   
      //if app is loading display loading else return all pics  
       !loading ? 
        (pics.length>0 && pics.map((pic) =>{
          return  <div className="info" key = {pic.id}>
                    <span className="close">
                       //I want to use onClick on this button to delete the specific image 
                      <span  className="inner-x">
                        &times;
                      </span>
                    </span>
                    <img src = {pic.src.original} alt ="img"/> 
                  </div>
        })
       
       ):<div> Loading </div>

    }
  </div>);
}

UPDATE : With the code below I remove the images from my list using hooks but they are not deleted from my picture :

function City(){


    const {loading , pics  ,query , setQuery}  = useFetch('athens');
    const [images , setImages] = useState([]);

    const removeImage = (id) =>{
      //images are inserted correctly cannot delete 
      setImages((oldState)=>oldState.filter((item)=> item.id !== id))
      images.map((im)=>console.log(im.id)) //images are deleted from list not from screen 
    }
  
    useEffect(()=>{
      setImages(pics);
    } , [pics]) 

    return (<div className="city-info">
      {
        !loading ? 
          (pics.length>0 && pics.map((pic) =>{
            return  <div className="info" key = {pic.id}>
                     <span className="close" onClick= {()=>removeImage(pic.id)} >
                        <span
                          className="inner-x">
                          &times;
                        </span>
                      </span>
                      <img src = {pic.src.original} alt ="img"/> 
                    </div>
          })
        
        ):<div> Loading ...  </div>

      }
    </div>);
  }

export default City;

Upvotes: 1

Views: 7719

Answers (1)

Cyrus Zei
Cyrus Zei

Reputation: 2660

So this is a simple local state example on how to remove items inside of an array

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

const allImages = [
  {
    id: 1,
    imgUrl: "https://via.placeholder.com/100"
  },
  {
    id: 2,
    imgUrl: "https://via.placeholder.com/100"
  },
  {
    id: 3,
    imgUrl: "https://via.placeholder.com/100"
  }
];

const App = () => {
  const [pics, setPics] = useState([]);

  const removeImage = (id) => {
    // this is the line that you are looking for
    setPics((oldState) => oldState.filter((item) => item.id !== id));
  };

  useEffect(() => {
    //fake fetch data
    setPics(allImages);
  }, []);
  return (
    <div className="App">
      {pics.map((pic) => {
        return (
          <div style={{ marginBottom: "100px" }}>
            {pic.id}
            <img
              src={pic.imgUrl}
              width="100px"
              height="100px"
              alt="placeholder grey 100px"
            />
            <button onClick={() => removeImage(pic.id)}>X</button>
          </div>
        );
      })}
    </div>
  );
};

export default App;

sandbox link

Upvotes: 3

Related Questions