Skip to content

Instantly share code, notes, and snippets.

@tharzeez
Created April 25, 2018 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tharzeez/0c58986e1dd7cb5a457e62f51a813f28 to your computer and use it in GitHub Desktop.
Save tharzeez/0c58986e1dd7cb5a457e62f51a813f28 to your computer and use it in GitHub Desktop.
This file describes how to set up the Ethereum JS API web3.js with the boilerplate Create React Native App

How to set up web3.js with CRNA

This is a simple guide to get you started with using the Ethereum Javascript API (web3.js) with the Create React Native App project. This is not an in-depth guide.

  1. Make sure you have Node version 6 or later installed, if not, get it on the Node website

    node --version

  2. Install Create React Native App

    npm install -g create-react-native-app

  3. Use create-react-native-app to create the project boilerplate

    create-react-native-app my-app

  4. Install node-libs-browser

    npm install --save node-libs-browser

  5. Create a file called rn-cli.config.js on the root of the project and add the following code into it:

    const extraNodeModules = require('node-libs-browser');
    
    module.exports = {
      extraNodeModules,
    };
  6. Create a file called global.js on the root of the project and add the following code into it:

    // Inject node globals into React Native global scope.
    global.Buffer = require('buffer').Buffer;
    global.process = require('process');
  7. Import the global.js file into your App.js file

    import './global';
  8. Install babel-preset-es2015

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

  9. Now we can install the web3.js api

    npm install --save web3

  10. Require the API in your App.js file

    const Web3 = require('web3');
  11. Add the following code inside your React component in App.js to get started with consuming the API. The code will print information of the latest block on the console.

    componentWillMount() {
      const web3 = new Web3(
        new Web3.providers.HttpProvider('https://mainnet.infura.io/')
      );
    
      web3.eth.getBlock('latest').then(console.log)
    }
  12. Test it

    npm start

    or

    npm run ios

    or

    npm run android

For more examples on the API usage, visit the web3.js documentation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment