Building a Visual Analytics Dashboard for the Celo Blockchain using React.js and Web3.js: A Step-By-Step Tutorial

Introduction:

As the adoption of blockchain technology continues to grow, there is a need for tools that can effectively analyze and visualize blockchain data for better understanding and decision-making. In this tutorial, developers will learn how to create a dynamic and interactive data visualization dashboard that provides real-time insights into the Celo blockchain. By leveraging the power of React.js and web3.js, you will be equipped with the technical skills to develop a user-friendly dashboard that displays various blockchain metrics and allows users to monitor and analyze the activity on the Celo blockchain.
We shall also explore how to fetch real-time blockchain data, integrate it with React.js components, and create dynamic visualizations that provide valuable insights into the Celo blockchain’s activity. By leveraging Celo’s Web3 provider, you will be able to fetch and update data in real-time, ensuring that your dashboard reflects the most recent information.
Throughout this tutorial, you will explore various blockchain metrics such as transaction volume, block confirmation times, and network activity. You will learn how to design intuitive visualizations that present these metrics in an engaging and informative manner. The dashboard you build will allow users to track trends, analyze patterns, and gain a deeper understanding of the Celo blockchain’s performance
If you are an experienced developer looking to expand your knowledge of blockchain technologies or a newcomer interested in exploring the potential of data visualization in the blockchain space, this tutorial will provide you with practical skills and hands-on experience. By the end of this tutorial, you will be well equipped to build a fully functional dashboard that enables users to visualize and analyze the activity on the Celo blockchain, empowering them to make informed decisions based on real-time data.
So, let’s dive in and embark on this exciting journey of building a visual analytics dashboard on the Celo blockchain using React.js and web3.js.

Setting Up the Project:

Let’s proceed with setting up the project for building the visual analytics dashboard for the Celo blockchain. Here’s a step-by-step guide to help you get started.
First, we set up the work environment by installing Node.js on our device. Visit the official Node.js website and download the latest stable version suitable for your operating system.
To initialize the project, In the project directory, run the following command to initialize a new Node.js project then we install react:

npm init -y

This will create a new (package.json) file for our project.

Installing React and React DOM packages in our project.

npm install react react-dom

Now we set up a new React.js project on the desired directory where the project is to be created and we navigate into the project directory:

npx create-react-app celo-dashboard
cd celo-dashboard

Here, we have a basic React.js project set up and ready to be customized for our visual analytics dashboard.
Secondly, we install additional dependencies and all necessary packages required for working with Celo and data visualization from the project directory and we connect to the Celo blockchain, these packages include web3.js for Celo blockchain interaction, @celo/contractkit for Celo-specific functionality, chart.js for data visualization, and react-chartjs-2 as a React wrapper for chart.js:

npm install web3 @celo/contractkit chart.js react-chartjs-2

Connecting to the Celo blockchain, we create a new file (celo.js) in the (src) directory of our project and we import the necessary dependency

import Web3 from 'web3';
import ContractKit from '@celo/contractkit';

We are utilizing the web3.js library to connect to the Celo blockchain network:

const web3 = new Web3('https:// /alfajores-forno.celo-testnet.org');
const kit = ContractKit.newKitFromWeb3(web3);
export { web3, kit };

Note:

The new Web3() creates a new instance of the Web3 object, which acts as our connection to the Celo blockchain.
The parameter ‘https:// /alfajores-forno.celo-testnet.org’ specifies the URL of the Celo network we want to connect to.
For the purpose of this tutorial, we are connecting to the Celo testnet. Testnets are separate networks that simulate the main network for development and testing purposes. You can always replace the URL with the appropriate Celo network URL depending on your needs, whether it’s the testnet or the mainnet.

ContractKit.newKitFromWeb3() is a function provided by the @celo/contractkit package which takes the web3 instance as a parameter and initializes a new instance of ContractKit.
ContractKit is a utility library provided by Celo that simplifies interacting with the Celo blockchain. It abstracts away some of the complexities and provides helpful functions and tools for interacting with contracts and performing common operations on the Celo blockchain. Savvy?

Thirdly, we handle Data Processing and Visualization:

We create a new index.js file which serves as the entry point of our React application:
It is responsible for rendering the App component and mounting it into the DOM. By calling ReactDOM.render(, document.getElementById(‘root’)), we shall be instructing React to render the App component and insert it into the element with the ID of ‘root’ in your HTML file. Basically, the index.js file is necessary to bootstrap and start our React application. It imports the App component from the App.js file and renders it in the DOM.

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));

We create an HTML file called index.html in the same directory and add the following block

<!DOCTYPE html>
<html>
  <head>
    <title>Celo Blockchain Analytics</title>
  </head>
  <body>
    <div id="root"></div>
    <script src="./dist/bundle.js"></script>
  </body>
</html>

The script tag is added to the HTML file which points to the bundled JavaScript file generated by the bundler. When the HTML file is loaded in a web browser, the bundled JavaScript code will be executed, rendering the React application in the specified ‘div’ element with the ID of ‘root’.
By running the bundler command, the JavaScript code from App.js and its dependencies will be bundled into a single file (e.g., bundle.js) that can be referenced in the HTML file for the application to work correctly.

Installing Babel and Webpack: Babel is a toolchain that helps convert modern JavaScript code into backward-compatible versions. Webpack is a bundler that bundles your code and its dependencies. Install Babel and Webpack along with their necessary plugins and loaders by running the following command:

npm install @babel/core @babel/preset-react babel-loader webpack webpack-cli --save-dev

Create a new file named babel.config.js in the root directory of your project.

module.exports = {
  presets: [
    '@babel/preset-env',
    '@babel/preset-react',
  ],
};

This configuration file specifies the presets for Babel to compile modern JavaScript code and React JSX syntax.

Create a new file named webpack.config.js in the root directory of your project.

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js',
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
        },
      },
    ],
  },
  resolve: {
    extensions: ['.js', '.jsx'],
  },
};

This configuration file specifies the entry point of your application (index.js), the output file (bundle.js), and the use of Babel loader to compile React code.

Install the necessary dependencies:

npm install babel-loader @babel/core @babel/preset-env @babel/preset-react webpack webpack-cli --save-dev
Update the scripts section in your package.json file:
"scripts": {
  "start": "webpack --mode development --watch",
  "build": "webpack --mode production"
},

This will allow us to run (npm start) to start the development server with live reloading, and (npm run build) to create a production-ready bundle.
With these configurations in place, you can now run npm start to start the development server and access your React application. The code will be compiled and bundled using Babel and Webpack, allowing you to write modern JavaScript and React code while maintaining compatibility with older browsers.
Create a new file name “App.js”

import React, { useState, useEffect } from 'react';
import { Line, Bar } from 'react-chartjs-2';
import { ContractKit } from '@celo/contractkit';
import Web3 from 'web3';

// Update the following values with your Celo blockchain details
const rpcEndpoint = 'https://alfajores-forno.celo-testnet.org';
const contractAddress = '0xYourContractAddress';
const abi = []; // Update with your contract's ABI

function App() {
  const [transactionVolumeData, setTransactionVolumeData] = useState({});
  const [blockConfirmationTimeData, setBlockConfirmationTimeData] = useState({});
  const [networkActivityData, setNetworkActivityData] = useState({});

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    try {
      const web3 = new Web3(rpcEndpoint);
      const kit = ContractKit.newKitFromWeb3(web3);

      // Fetching transaction volume data
      const transactionVolume = await fetchTransactionVolume(kit);
      const processedTransactionVolume = processTransactionVolume(transactionVolume);
      setTransactionVolumeData(processedTransactionVolume);

      // Fetching block confirmation time data
      const blockConfirmationTimes = await fetchBlockConfirmationTimes(kit);
      const processedBlockConfirmationTimes = processBlockConfirmationTimes(blockConfirmationTimes);
      setBlockConfirmationTimeData(processedBlockConfirmationTimes);

       // Fetching network activity data
      const networkActivity = await fetchNetworkActivity(kit);
      const processedNetworkActivity = processNetworkActivity(networkActivity);
      setNetworkActivityData(processedNetworkActivity);
    } catch (error) {
      console.error('Error fetching data from Celo blockchain:', error);
    }
  };

  const fetchTransactionVolume = async (kit) => {
    // Fetching transaction volume data from the Celo blockchain
    const contract = new kit.web3.eth.Contract(abi, contractAddress);
    const transactionVolume = await contract.methods.getTransactionVolume().call();
    return transactionVolume;
  };
    const processTransactionVolume = (transactionVolume) => {
// Processing transaction volume data into your chosen format for the chart
const processedData = {
  labels: ['Label 1', 'Label 2', 'Label 3'],
  datasets: [
    {
      label: 'Transaction Volume',
      data: [1000, 2000, 3000], // Swapping with your processed data
      backgroundColor: 'rgba(75,192,192,0.4)',
      borderColor: 'rgba(75,192,192,1)',
      borderWidth: 2,
    },
  ],
};
return processedData;
};

const fetchBlockConfirmationTimes = async (kit) => {
// Fetching block confirmation time data from the Celo blockchain
const contract = new kit.web3.eth.Contract(abi, contractAddress);
const blockConfirmationTimes = await contract.methods.getBlockConfirmationTimes().call();
return blockConfirmationTimes;
};

const processBlockConfirmationTimes = (blockConfirmationTimes) => {
// Processing block confirmation time data into your chosen format for the chart
const processedData = {
  labels: ['Label 1', 'Label 2', 'Label 3'],
  datasets: [
    {
      label: 'Block Confirmation Times',
      data: [10, 20, 30], // Swapping with processed data
      backgroundColor: 'rgba(75,192,192,0.4)',
      borderColor: 'rgba(75,192,192,1)',
      borderWidth: 2,
    },
  ],
};
return processedData;
};

const fetchNetworkActivity = async (kit) => {
// Fetching network activity data from the Celo blockchain
const contract = new kit.web3.eth.Contract(abi, contractAddress);
const networkActivity = await contract.methods.getNetworkActivity().call();
return networkActivity;
};

const processNetworkActivity = (networkActivity) => {
// Processing network activity data into the chosen format for the chart
const processedData = {
  labels: ['Label 1', 'Label 2', 'Label 3'],
  datasets: [
    {
      label: 'Network Activity',
      data: [500, 1000, 1500], // Swap with processed data
      backgroundColor: 'rgba(75,192,192,0.4)',
      borderColor: 'rgba(75,192,192,1)',
      borderWidth: 2,
    },
  ],
};
return processedData;
};

return (
<div className="App">
  <h1>Celo Blockchain Analytics Dashboard</h1>

  <div className="chart-container">
    <h2>Transaction Volume</h2>
    <Line data={transactionVolumeData} />
  </div>

  <div className="chart-container">
    <h2>Block Confirmation Times</h2>
    <Bar data={blockConfirmationTimeData} />
  </div>

  <div className="chart-container">
    <h2>Network Activity</h2>
    <Line data={networkActivityData} />
  </div>
</div>
);
} 

export default App; 

Here is a link to the repo containing the code base.

By following these steps, you should be able to run the dashboard locally and visualize the blockchain data. However, it’s important to note that the codebase provided in the tutorial serves as a starting point, and you may need to customize and extend it based on your other or specific requirements and creativity.
Before running the application, make sure to run the npm start command to start the development server with live reloading. You can access the React project by opening the provided URL in your web browser.

Conclusion

In this tutorial, we explored how to build a visual analytics dashboard on the Celo blockchain using React.js and web3.js. We learned how to fetch real-time blockchain data, integrate it with React.js components, and create dynamic visualizations to provide valuable insights into the Celo blockchain’s activity and allow interested users to track trends, analyze patterns, and gain a deeper understanding of the Celo blockchain’s performance. By following this tutorial, you have the basic skills in building a visual analytics dashboard on the Celo blockchain. You can now apply these concepts and techniques to analyze and visualize data from other blockchains or extend the functionality of the dashboard to suit any of your specific needs.

About the Author

ADEWALE EMMANUEL

is a crypto enthusiast and a Web 3.0 content creator. He is devoted to the mission of helping organizations with potential blockchain projects create educational content to attract and interest people in prospective decentralized financial infrastructures.

Connect with him on Twitter

5 Likes

Interesting ……

4 Likes

i look forward to this tutorial and i’ve showed my support.

3 Likes

Looking forward to this

5 Likes

Hi @9Manueldre22 ill be reviewing your piece

3 Likes