This tutorial will show you how to polyfill crypto
and other NodeJS modules globally in a React-Native environment.
Please note that these implementations are purely javascript and don't use native modules to generate random numbers
Run the following command
npm install --save node-libs-browser buffer process
# OR
yarn add node-libs-browser buffer process
From your root directory create a file called rn-cli.config.js
or simply add the following if it already exists
const extraNodeModules = require('node-libs-browser');
module.exports = {
extraNodeModules,
};
From your root directory create a file called global.js
or simply add the following if it already exists
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");
};
}
From your root directory add the previous global imports to either index.js
or both index.ios.js
and index.android.js
import { AppRegistry } from 'react-native';
import './global'
import App from './App';
AppRegistry.registerComponent('react-native-boilerplate', () => App);
Make sure your import global file before your App file
import React from "react";
import { StyleSheet, Text, View } from "react-native";
import crypto from "crypto";
export default class App extends React.Component<{}> {
state = {
key: null
};
componentDidMount() {
this.generateKey();
}
generateKey = async () => {
const key = await crypto.randomBytes(32);
console.log("key", key);
this.setState({ key });
};
render() {
return (
<View style={styles.container}>
<Text>Random Bytes</Text>
<Text>{this.state.key || "Generating..."}</Text>
</View>
);
}
}
Check out this example repo: https://github.com/markspereira/react-native-web3-boilerplate