ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Friday, November 4, 2022

[FIXED] How to deselect the values from state after selecting

 November 04, 2022     javascript, next.js, reactjs, thirdweb, typescript   

Issue

I am building an app in this after selecting the specific NFT a new div with extra content will show up. The selecting part is working fine but now I want it to be able to deselect it. This is the state

const [selectedNFT, setSelectedNFT] = useState<NFT>();

and this is the function for selecting the NFT

{ownedNfts?.data?.map((nft) => (
        <div
          onClick={() => setSelectedNFT(nft)}
          className={`flex flex-col space-y-2 card min-w-fit border-2 bg-gray-100 
          ${
            nft.metadata.id === selectedNFT?.metadata?.id
              ? "border-black scale-105 z-50"
              : "border-transparent"
          }`}
          key={nft.metadata.id}
        >

the onClick events populate the state but what I want is that after clicking on it again it should remove the data from the state making the state empty again


Solution

you can check if the nft is the current state, if so set it empty or whatever the desired value else set it to state .. (assuming you are putting only one nft in to selectedNFT)

onClick={() => {
   selectedNFT === nft ? setSelectedNFT("") : setSelectedNFT(nft)
}


Answered By - KcH
Answer Checked By - - David Marino (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix