Skip to content

Instantly share code, notes, and snippets.

@Gaurav8757
Created June 23, 2024 20:34
Show Gist options
  • Save Gaurav8757/28b7d7e181dd594c83ccf910117bb95d to your computer and use it in GitHub Desktop.
Save Gaurav8757/28b7d7e181dd594c83ccf910117bb95d to your computer and use it in GitHub Desktop.
import { useState } from 'react';
const App = () => {
const [albums, setAlbums] = useState([
{ userId: 1, title: 'Album', id: 1 },
{ userId: 1, title: 'omnis laborum odio', id: 2 },
{ userId: 1, title: 'omnis laborum odio 2', id: 3 },
{ userId: 2, title: 'aque aut omnis a', id: 4 },
{ userId: 2, title: 'aque aut omnis a laborum odio', id: 5 },
{ userId: 3, title: 'omnis laque aut omnis', id: 6 },
]);
const [selectedUserId, setSelectedUserId] = useState(null);
const [editingImageId, setEditingImageId] = useState(null);
const [newTitle, setNewTitle] = useState('');
const selectUserId = (userId) => {
setSelectedUserId(userId);
};
const deleteImage = (imageId) => {
setAlbums(albums.filter(album => album.id !== imageId));
};
const updateImageTitle = (imageId, newTitle) => {
setAlbums(albums.map(album => album.id === imageId ? { ...album, title: newTitle } : album));
setEditingImageId(null);
};
const userAlbums = selectedUserId ? albums.filter(album => album.userId === selectedUserId) : [];
return (
<div className="p-4">
<h1 className="text-2xl mb-4">Albums</h1>
<div className="grid grid-cols-2 gap-4">
{Array.from(new Set(albums.map(album => album.userId))).map(userId => (
<div
key={userId}
className="border p-2 cursor-pointer"
onClick={() => selectUserId(userId)}
>
<h2>User {userId}</h2>
</div>
))}
</div>
{selectedUserId && (
<div className="mt-4">
<h2 className="text-xl mb-2">User {selectedUserId} Albums</h2>
<div className="grid grid-cols-3 gap-4">
{userAlbums.map(image => (
<div key={image.id} className="relative border p-2">
<img src={`https://via.placeholder.com/150?text=${image.title}`} alt={image.title} />
<h3>{image.title}</h3>
<button
className="absolute top-0 right-0 bg-red-500 text-white px-2"
onClick={() => deleteImage(image.id)}
>
X
</button>
<button
className="absolute bottom-0 right-0 bg-blue-500 text-white px-2"
onClick={() => setEditingImageId(image.id)}
>
Edit
</button>
{editingImageId === image.id && (
<div className="absolute top-0 left-0 bg-white p-2 shadow-md">
<input
type="text"
value={newTitle}
onChange={(e) => setNewTitle(e.target.value)}
className="border p-1"
/>
<button
onClick={() => updateImageTitle(image.id, newTitle)}
className="bg-green-500 text-white px-2"
>
Save
</button>
</div>
)}
</div>
))}
</div>
</div>
)}
</div>
);
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment