Build a Simple NFT Marketplace with Solidity and React
NFTs (Non-Fungible Tokens) aren’t just about profile pictures—they’re a building block for ownership on-chain. Let’s build a basic NFT marketplace from scratch.
What You’ll Learn
- How ERC-721 works
- Minting NFTs
- Listing NFTs on a marketplace
- Buying NFTs using Ether
Smart Contract (Solidity)
solidity// SPDX-License-Identifier: MITpragma solidity ^0.8.0;import "@openzeppelin/contracts/token/ERC721/ERC721.sol";contract MyNFT is ERC721 {uint public nextTokenId;address public admin;constructor() ERC721("MyNFT", "MNFT") {admin = msg.sender;}function mint(address to) external {require(msg.sender == admin, "only admin");_safeMint(to, nextTokenId);nextTokenId++;}}
Marketplace Contract
soliditycontract NFTMarket {struct Listing {address seller;uint price;}mapping(uint => Listing) public listings;IERC721 public nft;constructor(address _nft) {nft = IERC721(_nft);}function list(uint tokenId, uint price) external {require(nft.ownerOf(tokenId) == msg.sender);listings[tokenId] = Listing(msg.sender, price);nft.transferFrom(msg.sender, address(this), tokenId);}function buy(uint tokenId) external payable {Listing memory listing = listings[tokenId];require(msg.value == listing.price);delete listings[tokenId];payable(listing.seller).transfer(msg.value);nft.transferFrom(address(this), msg.sender, tokenId);}}
Frontend (React + Ethers.js)
tsxconst buyNFT = async (tokenId: number) => {const market = new ethers.Contract(marketAddress, marketABI, signer);const price = await market.listings(tokenId).then(l => l.price);await market.buy(tokenId, { value: price });};
Screenshot
NFT UI
Try it Out
- Deploy to local Hardhat node
- Interact with it via Remix or a React app
What's Next?
- Add royalties
- Add auctions instead of fixed-price sales
- Use IPFS for decentralized metadata