A boilertemplate for using IPFS with React Native
node: v10.4.1
yarn: 1.12.3
react: 16.6.3
react-native: 0.57.8
IPFS HTTP Client: 29.0.0
Operating System
iOS Simuator: iPhone X iOS 12.1
git clone git@github.com:anakornk/ipfsWithReactNative.git
yarn install
ipfs daemon
echo "test" > testFile
ipfs add testFile
react-native run-ios
orreact-native run-android
- Create a new React Native Project
react-native init ipfsWithReactNative
- Install Node core modules for React Native
yarn add node-libs-react-native
yarn add vm-browserify
- In the project root directory, create
metro.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');
};
}
if (typeof global.self === "undefined") global.self = global;
- At the top of
index.js
, import these modules
import 'node-libs-react-native/globals';
import './globals';
- Install and Link
react-native-randombytes
yarn add react-native-randombytes
react-native link
- Install IPFS HTTP Client
yarn add ipfs-http-client
- Test IPFS
In App.js, import ipfs client.
import ipfsClient from 'ipfs-http-client';
Add the following two methods inside your App React component.
constructor(props) {
super(props);
this.ipfs = ipfsClient('localhost', '5001', { protocol: 'http' })
this.state = {
fileInText: 'empty'
}
}
componentDidMount() {
var that = this;
this.ipfs.cat('/ipfs/QmeomffUNfmQy76CQGy9NdmqEnnHU9soCexBnGU3ezPHVH', function (err, file) {
if (err) {
throw err
}
let text = file.toString('utf8')
that.setState({
fileInText: text
})
console.log(text)
})
}
Add the following code in your render method to display the text content of the file stored at '/ipfs/QmeomffUNfmQy76CQGy9NdmqEnnHU9soCexBnGU3ezPHVH'
<Text>{this.state.fileInText}</Text>
- Run
ipfs daemon
echo "test" > testFile
ipfs add testFile
react-native run-ios
The content of the testFile should be displayed.