This page looks best with JavaScript enabled

Develop Smart Contracts Using Remix And ReactJS

 ·  ☕ 10 min read  ·  ✍️ Adesh

In this tutorial, we will learn about developing smart contracts for ethereum using Remix and ReatJS.

Remix is a powerful, open-source tool that helps you write Solidity contracts straight from the browser. Written in JavaScript, Remix supports both usage in the browser and locally.

Remix also provides good tools for debugging, static analysis, and deployment all within the online environment. Here is the link for Remix documentation.

Remix Documentation

What’s a Smart Contract/Dapp?

The Ethereum virtual machine and smart contracts are key elements of Ethereum, and constitute its main attraction.

In Ethereum, smart contracts represent a piece of code written in a high-level language (Solidity, LLL, Viper) and stored as bytecode in the blockchain, in order to run reliably in a stack-based virtual machine (Ethereum Virtual Machine), in each node, once invoked.

The interactions with smart contract functions happen through transactions on the blockchain network, with their payloads executes in the Ethereum virtual machine, and the shared blockchain state updates accordingly.

Let’s start with Remix IDE

You can access the Remix IDE from your web browser without any special installation. Visit https://remix.ethereum.org/ and you’ll be presented with a complete IDE with a code editor and various panels for compiling, running and debugging your smart contracts. You’ll have a default example Ballot contract that you can play with.

Installing Remix IDE

You can also install Remix IDE on your machine by running the below command.

1
npm install remix-ide -g
1
remix-ide

Creating a Smart Contract

Let’s create a new file RemixContract.sol by clicking on + button on the File Explorer of Remix IDE.

This will open the Remix editor to write your smart contract code here.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
pragma solidity ^0.5.11;

contract RemixContract {
    string message;

    constructor() public {
        message = "Hello ZeptoBook";
    }

    function getMessage() public view returns(string memory) {
        return message;
    }

    function setMessage(string memory _message) public {
        message = _message;
    }

    function defaultMessage() public pure returns(uint256 num, string memory str){
        return (999, "This is RemixContract Default Message");
    }
}

In our RemixContract, I have created the following functions.

constructor() - this is a normal class constructor and we have set a default value of our message variable.

getMessage() - this function will return message variable to the caller.

setMessage() - this function will set the message by the caller.

defaultMessage() - this will return our hard-coded message to the caller.

Once we finish with writing our smart contract, it’s time to compile it to check any error. Let’s see how to compile a smart contract in Remix IDE.

Compiling a smart contract

Remix provides us the feature of compiling our smart contract.

Click on the Solidity compiler from the left menubar (red rectangular) to compile your smart contract.

On the top of the Solidity Compiler screen, it will show the selected compiler version. You can change to any other compiler version from this dropdown.

The second dropdown is for showing compiler language.

Compiling is triggered when you click the Compile button. If you want the file to be compiled each time the file is saved or when another file is selected - check the auto compile checkbox.

After each compilation, a list is updated with all newly compiled contracts. A compiled contract can be selected with the Contract pulldown menu. Multiple contracts are compiled when one contract imports other contracts. Selecting a contract will show information about that one.

When the “Compilation Details” button is clicked, a modal opens displaying detailed information about the currently selected contract.

Deploy and Run a smart contract

The Deploy & Run module allows you to send transactions to the current environment.

To get to the Run & Deploy module - click the run icon in the icon panel and then click on the Deploy button.

Remix Deploy

Once you click on the Deploy button, a transaction will happen and it will deploy our contract. The deployed contract will appear at the bottom of the screen.

Now, you can play with this contract’s functions here. Now, let’s move to the UI part where you are going to call these functions in our ReactJS app.

Creating a ReactJS app

Let’s create a ReactJS app named remixclient using the below command.

1
npx create-react-app remixclient
1
cd remixclient
1
npm run start

Adding Web3.js library in a React App

The web3.js library is a collection of modules which contain specific functionality for the ethereum ecosystem. The web3-eth is for the ethereum blockchain and smart contracts.

First you need to get web3.js into your project.

1
npm install web3

Connect Ganache with Remix

Ganache is used for setting up a personal Ethereum Blockchain to deploy contracts, develop your applications, and run tests. It gives you the ability to perform all actions you would on the main chain without the cost. It provides convenient tools such as advanced mining controls and a built-in block explorer. Basically Ganache runs local instance of Ethereum.

I have already installed Ganache on my local machine, so please install it before moving forward.

Open your Remix IDE, and you can see different options under Environment dropdown.

JavaScript VM -  This lets you run your contract directly in the browser using a JavaScript implementation of the Ethereum virtual machine (EVM). It is good for simple testing but each time when you reload the page it will start a new blockchain.

Injected Web3 -  Web3 is the interface for interacting with an Ethereum node. When you install Metamask, it injects web3 implementation into every web page. Using this option, you can use that injected implementation to deploy your contract to test networks or main Ethereum network.

Web3 Provider Using this option you can directly connect to an Ethereum node via HTTP. You can use this option to connect to Ganache or Geth. You will need to provide the URL address to the selected provider: Geth, Parity or any Ethereum client.

So let’s select Web3 provider from this dropdown, which prompts you whether you want to connect to Ethereum node. Clicking OK will gain prompt you to provide the Web3 provider endpoint.

It will ask you for Web3 provider endpoint url. Since we are going to use our local instance of Ganache, let’s open our Ganache.

Ganache RPC Url

Copy Ganache RPC server url and paste it inside the Web3 Provider Endpoint input box and click OK button.

Web3 provider endpoint

While connecting to Ganache, if you get below error, try to switch https to http from Remix url.

Not possible to connect t the Web3 provider. Make sure the provider is running and a connection is open (via IPC or RPC).

Remix Web3 provider Ganache

Now, we have successfully connected our Ganache to Remix and it is showing Ganache Network ID 5777 as well. Let’s re-deploy our contract as well.

Click on Deploy button again, and a transaction will happen. Since our Ganache is connected to Remix now, you can see the same transaction in Ganache as well.

transaction hash

Here is the transaction hash from Remix console.

contract transaction

You can also verify created contract’s Address here from Remix IDE in this transaction entry. Copy the deployed contract’s address from Remix IDE.

contract address from Remix

So we have succefully connected our Ganache to Remix and deployed the contract over there as well.

Create Contact’s ABI file in React App

Now, its time to work on our React app. First of all, we have to create a contract’s ABI json file in our src folder of React app.

Open VS Code and choose your project folder. Create a file ContractABI.js file inside src folder. Now, you will be wondering where to get the contract’s ABI file. So, here is the solution to get the contract’s ABI file.

Go to Remix IDE and click on ABI button to copy the contract’s ABI file.

Contract ABI

Inside the ContractABI.js file, assign this copied array to a react const ContractABI, something similar to below code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
export const ContractABI = [
  {
    constant: false,
    inputs: [
      {
        internalType: "string",
        name: "_message",
        type: "string"
      }
    ],
    name: "setMessage",
    outputs: [],
    payable: false,
    stateMutability: "nonpayable",
    type: "function"
  },
  {
    inputs: [],
    payable: false,
    stateMutability: "nonpayable",
    type: "constructor"
  },
  {
    constant: true,
    inputs: [],
    name: "defaultMessage",
    outputs: [
      {
        internalType: "uint256",
        name: "num",
        type: "uint256"
      },
      {
        internalType: "string",
        name: "str",
        type: "string"
      }
    ],
    payable: false,
    stateMutability: "pure",
    type: "function"
  },
  {
    constant: true,
    inputs: [],
    name: "getMessage",
    outputs: [
      {
        internalType: "string",
        name: "",
        type: "string"
      }
    ],
    payable: false,
    stateMutability: "view",
    type: "function"
  }
];

Changing App.js file

Now, after creating contract’s ABI json file, it’s time to change our App.js file to interact with all contract’s methods.

Here is the complete for App.js file.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import React, { useState } from "react";
import Web3 from "web3";
import { ContractABI } from "./ContractABI";

import "./App.css";

const web3 = new Web3(new Web3.providers.HttpProvider("HTTP://127.0.0.1:7545"));
web3.eth.defaultAccount = web3.eth.accounts[0];

const RemixContract = new web3.eth.Contract(
  ContractABI,
  "0x677BB4A98566ab3e12E7178A0C06Ae3A3988A2A7"
);

function App() {
  const [message, setMessage] = useState("");

  const setData = async e => {
    e.preventDefault();
    const accounts = await window.ethereum.enable();
    const account = accounts[0];

    const gas = await RemixContract.methods.setMessage(message).estimateGas();
    const result = await RemixContract.methods
      .setMessage(message)
      .send({ from: account, gas });
    console.log(result);
  };

  const getDefaultData = async e => {
    RemixContract.methods
      .defaultMessage()
      .call()
      .then(console.log);
  };

  const getData = async e => {
    RemixContract.methods
      .getMessage()
      .call()
      .then(console.log);
  };

  return (
    <div className="App">
      <header className="App-header">
        <form onSubmit={setData}>
          <label>
            Set Message:
            <input
              type="text"
              name="message"
              value={message}
              onChange={e => setMessage(e.target.value)}
            />
          </label>
          <input type="submit" value="Set Message" />
        </form>
        <br />
        <button onClick={getData} type="button">
          Get Message
        </button>
        <button onClick={getDefaultData} type="button">
          Get Default Message
        </button>
      </header>
    </div>
  );
}

export default App;
Note: As purpose of this tutorial is to illustrate to you how to connect Remix with React & Ganache, so I am not going into the details of this code. Change your Ganache RPC Server Url and appropriate Contract’s address.

Our UI will look like below.

react UI

Test our React app

1. Get default message

Click on Get Default Message button and you will see the result in the browser’s console window.

2. Get message

Click on Get Message button and you will see the result in the browser’s console window.

3. Set custom message

Now, we are going to set the custom message and get it again. When you click on Set Message button, a transaction will happen and it will be shown in the console window.

You can verify the same transaction entry in your Ganache server as well. Below is the transaction hash:

Ganache Transaction entry

4. Get custom message

Click on Get Message button to get our custom message.

You can also verify your custom message in Remix IDE. Go to Remix IDE and click on getMessage button.

Further Reading

Deploy Your First Smart Contract With Truffle

Create Your First BlockChain Ethereum DAPP With React

Share on

Adesh
WRITTEN BY
Adesh
Technical Architect