I'm using react-modal library to create modals, I have mapped objects representing music albums. I want to open modal with a button next to the object and call a function with all the properties of this object. The problem is that when I'm trying to do this, inside of Modal it always calls function with last mapped object's properties. This is how it looks:
const [modalIsOpen, setIsOpen] = useState(false);
(...)
function openModal() {
setIsOpen(true);
}
function closeModal() {
setIsOpen(false);
}
(...)
<div className="card-body">
{album.map(album =>
<div key={album}>
<img src={album.imageUrl} alt="cover"/>
{album.artistName} - {album.albumName}
<button onClick={() => deleteBought(album)}>Delete from bought</button> // this one works well
<button onClick={openModal}>Delete from bought (modal)</button>
<Modal
isOpen={modalIsOpen}
onRequestClose={closeModal}
style={customStyles}
contentLabel="Example Modal"
>
<button onClick={() => closeModal()}>Close</button>
<button onClick={() => {deleteBought(album);closeModal()}}>Delete</button> // this one passes properties of last object
</Modal>
</div>
)}
</div>
How can I refer to a correct object in the opened Modal?
CodePudding user response:
You can do this, and you do not need to put the Modal component in the map
const [modalIsOpen, setIsOpen] = useState(false);
const [activeAlbum, setActiveAlbum] = useState(null);
const album = [
{ id: 1, artistName: "name1", albumName: "albumName1" },
{ id: 2, artistName: "name2", albumName: "albumName2" }
];
const AlbumModal = ({ album }) => (
<Modal
isOpen={modalIsOpen}
onRequestClose={() => setIsOpen(false)}
contentLabel="Example Modal"
>
<h1>{album.albumName}</h1>
<button onClick={() => setIsOpen(false)}>Close</button>
<button onClick={() => setIsOpen(false)}>Delete</button>
</Modal>
);
return (
<div className="card-body">
{album.map((album) => (
<div key={album}>
{<img src={album.imageUrl} alt="cover"/>}
{album.artistName} - {album.albumName}
<button
onClick={() => {
setIsOpen(true);
setActiveAlbum(album);
}}
>
Delete from bought (modal)
</button>
</div>
))}
{activeAlbum && <AlbumModal album={activeAlbum} />}
</div>
);