Create a Dapp

Building a React App for Solidity Contracts with Vite, Tailwind, and Web3

This guide will show you how to create a React app to interact with Ethereum smart contracts using Web3.js. We will set up a Vite project with Tailwind CSS styling and build interfaces for two example contracts: a Vending Machine and a Lottery.

Steps to Set Up the React App

Step 1: Initialize a Vite Project

Run the following commands to create a Vite React app, install dependencies, and start the development server:

npm init vite@latest
cd <project name>
npm install
npm run dev

Step 2: Install and Configure Tailwind CSS

To add Tailwind CSS, install the necessary packages:

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init

In the tailwind.config.js file, configure Tailwind to remove unused styles in production by specifying the files to scan:

module.exports = {
  content: [
    "./index.html",
    "./src/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

Add the Tailwind directives to your CSS file (e.g., src/index.css):

Step 3: Install Web3.js

Install Web3.js to connect your React app to the Ethereum blockchain:


Vending Machine Contract

The Vending Machine smart contract allows users to purchase items with Ether and allows the owner to restock inventory.

Lottery Contract

The Lottery smart contract allows players to join by paying an entry fee, with the contract owner able to pick a winner at random.


Integrating the Contracts with the React App

  1. Set up Web3 Provider and ABI files for each contract in src/contracts/.

  2. Create components to interact with the contracts.

Example React Component for Vending Machine


Testing the Contracts with Hardhat

Step 1: Install Hardhat

If you haven’t already:

Step 2: Create Test Files

Create test files for each contract. For instance, a VendingMachine test might look like this:

Run the tests with:

Last updated