How to Create DApps Using React for Frontend and Ruby on Rails for Backend

Introduction

Decentralized Applications (DApps) are a new type of application that leverages blockchain technology. In this article, we will explain in detail how to create DApps using React for the frontend and Ruby on Rails for the backend.

Prerequisites

  • Basic programming knowledge (JavaScript, Ruby, HTML, CSS)

  • Node.js and npm installed

  • Ruby and Rails installed

  • An Ethereum wallet like MetaMask installed

1. Setting Up the Project

Setting Up the Frontend (React)

First, create a new React project using Create React App.

npx create-react-app my-dapp
cd my-dapp

Next, install the necessary libraries.

npm install web3

Setting Up the Backend (Ruby on Rails)

Next, create a Rails project.

rails new my-dapp-backend --api
cd my-dapp-backend

Add the following lines to your Gemfile and install the gems.

gem 'rack-cors', :require => 'rack/cors'
gem 'ethereum.rb'
bundle install

2. Configuring CORS

Add the following code to config/application.rb to configure CORS.

module MyDappBackend
  class Application < Rails::Application
    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*',
          headers: :any,
          methods: [:get, :post, :options, :delete, :put]
      end
    end
  end
end

3. Creating and Deploying the Smart Contract

Creating Smart Contract in Solidity

Next, create a smart contract using Solidity. Here is a simple example.

// contracts/MyContract.sol
pragma solidity ^0.8.0;

contract MyContract {
    string public message;

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

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

Compiling and Deploying the Contract

Use tools like Truffle or Hardhat to compile the contract and deploy it to a local Ethereum network (such as Ganache).

truffle compile
truffle migrate

4. Configuring the Backend

Creating Endpoints to Interact with the Contract

Create endpoints in Rails to interact with Ethereum.

# app/controllers/contracts_controller.rb
class ContractsController < ApplicationController
  def set_message
    # Add logic to interact with Ethereum here
  end

  def get_message
    # Add logic to interact with Ethereum here
  end
end

Set up the routing.

# config/routes.rb
Rails.application.routes.draw do
  post 'set_message', to: 'contracts#set_message'
  get 'get_message', to: 'contracts#get_message'
end

5. Implementing the Frontend

Creating a Form in React

Create the user interface in React.

// src/App.js
import React, { useState } from 'react';
import Web3 from 'web3';

function App() {
  const [message, setMessage] = useState('');
  const [newMessage, setNewMessage] = useState('');

  const web3 = new Web3(Web3.givenProvider || "http://localhost:8545");

  const handleSubmit = async (event) => {
    event.preventDefault();
    // Add logic to interact with the smart contract here
  };

  return (
    <div className="App">
      <header className="App-header">
        <form onSubmit={handleSubmit}>
          <input
            type="text"
            value={newMessage}
            onChange={(e) => setNewMessage(e.target.value)}
          />
          <button type="submit">Set Message</button>
        </form>
        <p>Message: {message}</p>
      </header>
    </div>
  );
}

export default App;

Interacting with the Backend

Interact with the backend in React.

const handleSubmit = async (event) => {
  event.preventDefault();
  const accounts = await web3.eth.getAccounts();
  const contract = new web3.eth.Contract(ABI, contractAddress);
  await contract.methods.setMessage(newMessage).send({ from: accounts[0] });

  const response = await fetch('http://localhost:3001/get_message');
  const data = await response.json();
  setMessage(data.message);
};

Conclusion

With this, you have created a simple DApp using React and Ruby on Rails. In a real project, you need to consider security, performance, scalability, and other factors, but the basic structure will be as described here. Try applying this to your own projects.

Did you find this article valuable?

Support Atsushi Ishida by becoming a sponsor. Any amount is appreciated!