A boilertemplate for using Web3 1.x with React Native
node: v10.4.1
yarn: 1.12.3
react: 16.6.3
react-native: 0.57.8
web3: 1.0.0-beta.37
Operating System
iOS Simuator: iPhone X iOS 12.1
Android Simulator: AVD Nexus 5X API 27
git clone [email protected]:anakornk/web3WithReactNative.git
yarn install
ganache-cli
react-native run-ios
orreact-native run-android
- Create a new React Native Project
react-native init web3WithReactNative
- Install Node core modules for React Native
yarn add node-libs-react-native
yarn add vm-browserify
- In the project root directory, create
rn-cli.config.js
const nodeLibs = require('node-libs-react-native');
nodeLibs.vm = require.resolve('vm-browserify');
module.exports = {
resolver: {
extraNodeModules: nodeLibs
},
};
- In the project root directory, create
globals.js
import url from "url";
global.URL = class URL {
constructor(inputUrl) {
return url.parse(inputUrl);
}
};
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');
};
}
- At the top of
index.js
, import these modules
import 'node-libs-react-native/globals';
import './globals.js';
- Install and Link
react-native-randombytes
yarn add react-native-randombytes
react-native link
- Install web3
yarn add web3
- Import and Test web3
In App.js, import web3.
import Web3 from 'web3';
Add the following code inside your App React component. The code will print out information of the latest block and accounts
componentWillMount() {
this.web3 = new Web3('ws://localhost:8545');
this.web3.eth.getBlock('latest').then(console.log).catch(console.log);
this.web3.eth.getAccounts(function(error,res) {
if(!error) {
console.log(res);
} else {
console.log(error);
}
});
}
- Run
ganache-cli
react-native run-ios
- https://gist.github.com/dougbacelar/29e60920d8fa1982535247563eb63766
- parshap/node-libs-react-native#6
- facebook/react-native#16434
- The above code uses websocket provider, if you want to use http provider, you will need to edit a node_modules file since there's currently a problem with XMLHttpRequest. For more information, please see the link below:
souldreamer/xhr2-cookies#7 vm-browserify
is not a RN-compatible polyfill for vm, but works for now. For more information, please see the link below: parshap/node-libs-react-native#6