Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NEXTJS Conditional Statement not working inside of a map

When I compile this code, it gives me an error saying that I am not properly closing the a tag.

When I remove the conditional statement on the following code, it works fines:

{nid[index] != undefined ? (  
 <a target= "_blank" rel="noreferrer" href={polygonURL + Cont[index] + "/" + nid[index]}>
) : (
 <a target= "_blank" rel="noreferrer" href={unkpolygonURL + Cont[index]}>

)}

import styles from "../styles/Home.module.css";
import React, { useEffect, useState, useRef } from "react";
import { useAddress, useMetamask, useDisconnect } from "@thirdweb-dev/react";
import Spinner from "./Spinner";

export default function NFT() {

  const address = useAddress();
  let image = "";
let total = 0;
  const [title, setTitle] = useState([]);
  const [Img, setImg] = useState([]);
  const [Cont, setCont] = useState([]);
  const [nid, setNid] = useState([]);
const[totalNFT, setTotalNFT] = useState(0);

let page = "";

const polygonURL = "https://opensea.io/assets/matic/";
const unkpolygonURL = "https://opensea.io/assets?search[query]=";



  const getPolygonNFT = async (str) => {

    // const api = 'https://eth-mainnet.alchemyapi.io/v2/demo/getNFTs/?owner=0xfae46f94ee7b2acb497cecaff6cff17f621c693d';
    const api = `https://polygon-mainnet.g.alchemyapi.io/v2/demo/getNFTs/?owner=` + str;
    const response = await fetch(api);
    const data = await response.json();
    
    console.log(data);
    let total = data.totalCount;
    let firsttotal = data.ownedNfts.length;
    setTotalNFT(data.ownedNfts.length);
    // setPage(data.pageKey);
    let page = data.pageKey;


    for (var i = 0; i < firsttotal; i++){
      setImg(oldArray => [...oldArray, data.ownedNfts[i].media[0].gateway]);
      setTitle(oldArray => [...oldArray, data.ownedNfts[i].metadata.name]);
      setCont(oldArray => [...oldArray, data.ownedNfts[i].contract.address]);
    setNid(oldArray => [...oldArray, data.ownedNfts[i].metadata.edition])
    
    } 

    let j = true;
    let count = 0;

    while (j){

       
      
if (page != undefined){



  const api = `https://polygon-mainnet.g.alchemyapi.io/v2/demo/getNFTs/?owner=` + str + `&pageKey=` + page;

  const response = await fetch(api);
  const data = await response.json();
console.log(data)

 page = data.pageKey;
  let nexttotal = data.ownedNfts.length;
  for (var k = count; k < nexttotal+count ; k++){
    setImg(oldArray => [...oldArray, data.ownedNfts[k].media[0].gateway]);
    setTitle(oldArray => [...oldArray, data.ownedNfts[k].metadata.name]);
    setCont(oldArray => [...oldArray, data.ownedNfts[k].contract.address]);
    setNid(oldArray => [...oldArray, data.ownedNfts[k].metadata.edition])

  }




  } else {
    j = false;
  }
  
  }

    }

  useEffect(() => {
    getPolygonNFT(address);
  }, []);


  return (
<main className="inside p-10 shadow-xl shadow-gray-400/20">

{totalNFT === 0 ? (
<>
{totalNFT !== 0 ? (
  <h1 className="mb-10 text-4xl font-extralight" > 
<span className='text-slate-300 font-extrabold underline decoration-neutral-600'>You do not own any NFTs.</span>
</h1>
) : (
<Spinner />
)}  
</>
) : (
<>
<div className="grid space-x-3 md:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4">

{title.map ( (name, index) => {
      return (   
<div name={index} key={index}>


{nid[index] != undefined ? (  
 <a target= "_blank" rel="noreferrer" href={polygonURL + Cont[index] + "/" + nid[index]}>
) : (
 <a target= "_blank" rel="noreferrer" href={unkpolygonURL + Cont[index]}>

)}


<div className="flex flex-col items-center cursor-pointer transition-all duration-200 hover:scale-105">
<img className="h-80 w-80 rounded-2xl object-cover" src={Img[index]} alt="" 
  onError={({ currentTarget }) => {
    currentTarget.onerror = null; // prevents looping
    currentTarget.src="https://user-images.githubusercontent.com/24848110/33519396-7e56363c-d79d-11e7-969b-09782f5ccbab.png";
  }}
/>
<div className="p-5">
<h2 className="text-gray-100 text-3xl">{title[index]}</h2>
<p className="mt-2 text-sm text-gray-400">{Cont[index]}</p>
</div>
</div>
</a>
</div>
)
    })  
  }
      </div>
  </>
  )

}
</main>
  )}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

import styles from "../styles/Home.module.css";
import React, { useEffect, useState, useRef } from "react";
import { useAddress, useMetamask, useDisconnect } from "@thirdweb-dev/react";
import Spinner from "./Spinner";

export default function NFT() {
  const address = useAddress();
  let image = "";
  let total = 0;
  const [title, setTitle] = useState([]);
  const [Img, setImg] = useState([]);
  const [Cont, setCont] = useState([]);
  const [nid, setNid] = useState([]);
  const [totalNFT, setTotalNFT] = useState(0);

  let page = "";

  const polygonURL = "https://opensea.io/assets/matic/";
  const unkpolygonURL = "https://opensea.io/assets?search[query]=";

  const getPolygonNFT = async (str) => {
    // const api = 'https://eth-mainnet.alchemyapi.io/v2/demo/getNFTs/?owner=0xfae46f94ee7b2acb497cecaff6cff17f621c693d';
    const api =
      `https://polygon-mainnet.g.alchemyapi.io/v2/demo/getNFTs/?owner=` + str;
    const response = await fetch(api);
    const data = await response.json();

    console.log(data);
    let total = data.totalCount;
    let firsttotal = data.ownedNfts.length;
    setTotalNFT(data.ownedNfts.length);
    // setPage(data.pageKey);
    let page = data.pageKey;

    for (var i = 0; i < firsttotal; i++) {
      setImg((oldArray) => [...oldArray, data.ownedNfts[i].media[0].gateway]);
      setTitle((oldArray) => [...oldArray, data.ownedNfts[i].metadata.name]);
      setCont((oldArray) => [...oldArray, data.ownedNfts[i].contract.address]);
      setNid((oldArray) => [...oldArray, data.ownedNfts[i].metadata.edition]);
    }

    let j = true;
    let count = 0;

    while (j) {
      if (page != undefined) {
        const api =
          `https://polygon-mainnet.g.alchemyapi.io/v2/demo/getNFTs/?owner=` +
          str +
          `&pageKey=` +
          page;

        const response = await fetch(api);
        const data = await response.json();
        console.log(data);

        page = data.pageKey;
        let nexttotal = data.ownedNfts.length;
        for (var k = count; k < nexttotal + count; k++) {
          setImg((oldArray) => [
            ...oldArray,
            data.ownedNfts[k].media[0].gateway,
          ]);
          setTitle((oldArray) => [
            ...oldArray,
            data.ownedNfts[k].metadata.name,
          ]);
          setCont((oldArray) => [
            ...oldArray,
            data.ownedNfts[k].contract.address,
          ]);
          setNid((oldArray) => [
            ...oldArray,
            data.ownedNfts[k].metadata.edition,
          ]);
        }
      } else {
        j = false;
      }
    }
  };

  useEffect(() => {
    getPolygonNFT(address);
  }, []);

  return (
    <main className="inside p-10 shadow-xl shadow-gray-400/20">
      {totalNFT === 0 ? (
        <>
          {totalNFT !== 0 ? (
            <h1 className="mb-10 text-4xl font-extralight">
              <span className="text-slate-300 font-extrabold underline decoration-neutral-600">
                You do not own any NFTs.
              </span>
            </h1>
          ) : (
            <Spinner />
          )}
        </>
      ) : (
        <div className="grid space-x-3 md:grid-cols-2 lg:grid-cols-3 2xl:grid-cols-4">
          {title.map((name, index) => {
            return (
              <div name={index} key={index}>
                {nid[index] != undefined ? (
                  <a
                    target="_blank"
                    rel="noreferrer"
                    href={polygonURL + Cont[index] + "/" + nid[index]}
                  >
                    <div className="flex flex-col items-center cursor-pointer transition-all duration-200 hover:scale-105">
                      <img
                        className="h-80 w-80 rounded-2xl object-cover"
                        src={Img[index]}
                        alt=""
                        onError={({ currentTarget }) => {
                          currentTarget.onerror = null; // prevents looping
                          currentTarget.src =
                            "https://user-images.githubusercontent.com/24848110/33519396-7e56363c-d79d-11e7-969b-09782f5ccbab.png";
                        }}
                      />
                      <div className="p-5">
                        <h2 className="text-gray-100 text-3xl">
                          {title[index]}
                        </h2>
                        <p className="mt-2 text-sm text-gray-400">
                          {Cont[index]}
                        </p>
                      </div>
                    </div>
                  </a>
                ) : (
                  <a
                    target="_blank"
                    rel="noreferrer"
                    href={unkpolygonURL + Cont[index]}
                  >
                    <div className="flex flex-col items-center cursor-pointer transition-all duration-200 hover:scale-105">
                      <img
                        className="h-80 w-80 rounded-2xl object-cover"
                        src={Img[index]}
                        alt=""
                        onError={({ currentTarget }) => {
                          currentTarget.onerror = null; // prevents looping
                          currentTarget.src =
                            "https://user-images.githubusercontent.com/24848110/33519396-7e56363c-d79d-11e7-969b-09782f5ccbab.png";
                        }}
                      />
                      <div className="p-5">
                        <h2 className="text-gray-100 text-3xl">
                          {title[index]}
                        </h2>
                        <p className="mt-2 text-sm text-gray-400">
                          {Cont[index]}
                        </p>
                      </div>
                    </div>
                  </a>
                )}
              </div>
            );
          })}
        </div>
      )}
    </main>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading