Home > Software engineering >  Open a modal in React when a user wants to delete an image
Open a modal in React when a user wants to delete an image

Time:08-28

import getPhotoUrl from 'get-photo-url'
import { useLiveQuery } from 'dexie-react-hooks'
import { db } from '../dexie'

const Gallery  = () => {
    const allPhotos = useLiveQuery(() => db.gallery.toArray(), [])
    
    const addPhoto = async () => {
        db.gallery.add({
            url: await getPhotoUrl('#addPhotoInput'),
        })

    }

    const removePhoto = (id) => {
        db.gallery.delete(id)
    }

    return (
        <>
            <input type="file" name="photo" id="addPhotoInput"/>
            <label htmlFor="addPhotoInput" onClick={addPhoto}>
                <i className="add-photo-button fas fa-plus-square"></i>
            </label>

            <section className='gallery'>
                {!allPhotos && <p>Loading...</p>}
                {allPhotos?.map((photo) => (
                <div className="item" key={photo.id}>
                    <img src ={photo.url} className="item-image" alt=""/>
                    <button className="delete-button" onClick= {() => removePhoto(photo.id)}>Delete</button>
                </div>
                ))}
            </section>
        
        </>
    )

}

export default Gallery

Please I need help in the above code. I'm building an instagram clone with React. I have a gallery component in which I want to delete specific images. I would like a modal to pop up asking to confirm if a user would like to delete the image. If they say yes, the image would be deleted, while no leaves the image.

CodePudding user response:

The easiest way is to use the default browser window.confirm

<button className="delete-button" onClick= {() => {
  const deleteConfirmed = window.confirm('Are you sure?');
  if (deleteConfirmed) {
    removePhoto(photo.id)
  } 
}}>Delete</button>

But if you want to customize the popup, you can create your own or use any component-library like material-ui.

  • Related