Setting up Web3.js with CRNA: A Beginner's Guide

Setting up Web3.js with CRNA: A Beginner's Guide

This straightforward guide will walk you through the steps to utilize the Ethereum Javascript API (web3.js) in conjunction with the Create React Native App (CRNA) project. Please note, this guide is intended to get you started and is not comprehensive.

In a nutshell: For those eager to dive right in, I have prepared a ready-to-use project. It's set up to work immediately after installation.

Step-by-step Installation: First and foremost, ensure you have Node version 6 or later installed on your machine. If not, you can download it from the official Node website.

Verify your Node version by typing:

node --version

Next, install Create React Native App:

npm install -g create-react-native-app

Utilize create-react-native-app to generate your project's skeleton:

create-react-native-app my-app

Proceed to install node-libs-browser:

npm install --save node-libs-browser

In the root directory of your project, create a file named rn-cli.config.js and insert the following code:

const extraNodeModules = require('node-libs-browser');

module.exports = {
  extraNodeModules,
};

Create another file in the root directory, this time named global.js, and add the code below:

// Inject node globals into React Native global scope.
global.Buffer = require('buffer').Buffer;
global.process = require('process');

if (typeof btoa === 'undefined') {
  global.btoa = function (str) {
    return new Buffer(str, 'binary').toString('base64');
  };
}

if (typeof atob === 'undefined') {
  global.atob = function (b64Encoded) {
    return new Buffer(b64Encoded, 'base64').toString('binary');
  };
}

Next, import the global.js file into your App.js file:

import './global';

Install babel-preset-es2015:

npm install --save-dev babel-cli babel-preset-es2015

At this point, we are ready to install the web3.js API:

npm install --save web3

In your App.js file, require the API:

const Web3 = require('web3');
import React, { useEffect } from 'react';

To start interacting with the API, add the following code within your React component in App.js. The code will display the details of the most recent block in the console:

useEffect(() => {
  const web3 = new Web3(
    new Web3.providers.HttpProvider('https://zmok.io/mainnet/YOUR_APP_ID')
  );

  web3.eth.getBlock('latest').then(console.log);
}, []);

Finally, test your setup:

npm start

or

npm ios

or

npm android

For additional examples on how to utilize the API, be sure to check out the web3.js documentation.

Enhance your Ethereum development journey with ZMOK, a trusted and efficient Ethereum JSON-RPC provider.