Selecting an NFT

The globals.css import will be done in App.js, the rest of the code from this page will be inserted on the MainMenu.js page.

Making it possible for the user to click any of the NFTs means we have to import some styles for the selected NFT’s appearance. Please copy globals.css file into the styles directory. After this, import it into the main App.js file.

import './styles/globals.css';

Update styles for rendered NFTs

After this, please add classNames to the <span> and <img> tags containing the NFT info. The result should be the following:

{NFTsOwned.map((nftId) => (
  <span id={`nft${nftId}`} key={nftId} className="characterContainer">
    <img
      className="characterImg"
      src={`https://stacksgamefi.mypinata.cloud/ipfs/QmNz74TN66hgi9X4wZ1ch9hXKxaywG5soEQPMfDqEMLVsd/${nftId}.png`}
      alt={`character ${nftId}`}
    ></img>
    {`NFT#${nftId}`}
  </span>
))}

In order to memorize the user’s selected NFT, we will need a state to keep track of it, initialized by '' value inside MainMenu. The initial value on the MainMenu component’s load means the user has not selected any NFT.

const [selectedNFT, setSelectedNFT] = useState('');

Change styles based on selected NFT

We want the selection to stand out the other NFTs. For this, we will create a changeSelection constant which will take two parameters: the previous selected NFT and the currently selected one:

const changeSelection = (nft, localSelectedNFT) => {
  document.getElementById(`nft${localSelectedNFT}`)?.classList.remove('card-selected');
  document.getElementById(`nft${nft}`)?.classList.add('card-selected');
};

This constant will make sure that the new clicked NFT will be highlighted, and the previous one not anymore. Next we will need an event handler, for handling the user’s clicks inside the NFTs interface. This handler first calls the changeSelection, making the CSS changes needed for the UI appearance. Let’s make an alert() to see if the clicked NFT’s id is the same to the one the constant uses as a parameter. Least but not last, we have to set the selectedNFT's constant value to the id received as a parameter.

const handleClickNFT = (id) => {
  changeSelection(id, selectedNFT);
  alert(`selected NFT:  ${id}`);
  setSelectedNFT(id);
};

Now that we have created the handler, let’s stick it to the corresponding HTML tag’s onClick function (line 7):

{NFTsOwned.map((nftId) => (
  <span id={`nft${nftId}`} key={nftId} className="characterContainer">
    <img
      className="characterImg"
      src={`https://stacksgamefi.mypinata.cloud/ipfs/QmNz74TN66hgi9X4wZ1ch9hXKxaywG5soEQPMfDqEMLVsd/${nftId}.png`}
      alt={`duck ${nftId}`}
      width="50"
      onClick={() => handleClickNFT(nftId)}
    ></img>
    {`NFT#${nftId}`}
  </span>
))}

This is the branch with the changes done:

You can check the exact changes in this commit referring to them

Last updated