DisplayNfts.tsx 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import Image from "next/image"
  2. import { useWallet } from "@solana/wallet-adapter-react"
  3. import { useNftState } from "@/contexts/NftProvider"
  4. import { useState } from "react";
  5. export class Nft {
  6. name: string;
  7. url: string;
  8. constructor() {
  9. this.url = "";
  10. this.name = "";
  11. }
  12. }
  13. const DisplayNfts = () => {
  14. const { publicKey } = useWallet()
  15. const { nftState: nftState } = useNftState()
  16. const [showItems, setShowItems] = useState(false);
  17. const handleButtonClick = () => {
  18. setShowItems(!showItems);
  19. };
  20. var myNfts = new Array<Nft>();
  21. if (nftState != null) {
  22. for (var i = 0; i < nftState.items.length; i++) {
  23. try {
  24. const nftData = nftState.items[i];
  25. let nft = new Nft();
  26. nft.name = nftData.content.metadata.name;
  27. nft.url = nftData.content.links.image;
  28. myNfts.push(nft);
  29. } catch (error) {
  30. console.log(error);
  31. }
  32. }
  33. }
  34. function onNftClickedCallback(nft: Nft): void {
  35. window.alert("Nft clicked: " + nft.name);
  36. }
  37. return (
  38. <>
  39. {nftState && publicKey && (
  40. <div>
  41. <button onClick={handleButtonClick}>Show NFTs</button>
  42. {showItems && (
  43. <div className="flex flex-row space-x-5 overflow-x-auto self-end place-items-center justify-center ... ">
  44. {myNfts.map((nft) => (
  45. <div key={nft.name}>
  46. <p className="text-sky-400 truncate ...">{nft.name}</p>
  47. <div className="flex flex-row place-items-center ...">
  48. {nft.url ? (
  49. <Image
  50. onClick={() => onNftClickedCallback(nft)}
  51. src={nft.url}
  52. alt="NFT Icon"
  53. width={64}
  54. height={64}
  55. />
  56. ) : (
  57. <div>Error loading image</div>
  58. )}
  59. </div>
  60. </div>
  61. ))}
  62. </div>
  63. )}
  64. </div>
  65. )}
  66. </>
  67. );
  68. }
  69. export default DisplayNfts