Multiple image uploads in React - android

I am building an e-commerce mobile app with react native, and I want to make it possible for the users to upload multiple images of a product, but I don't know the best package to install for this to work, I don't even know if I should do it from scratch, this question is more like an advise question just to guide me, Please any help will be really great, Thanks

I use react-native-image-cropper-picker and it cuts it. It allows multiple picking, base64, cropping among others.
To pick multiple you can do as follows:
pickMultiple() {
ImagePicker.openPicker({
multiple: true,
waitAnimationEnd: false,
includeExif: true,
forceJpg: true,
}).then(images => {
this.setState({
imagesArray: images.map(i => {
console.log('received image', i);
return {uri: i.path, width: i.width, height: i.height, mime: i.mime};
})
});
}).catch(e => alert(e));
}

Related

Render many charts without lags on React Native

I'need to show user feed with items where every item contain a chart.
Now I use react-native-svg-charts:
<LineChart
style={{ height: 150, position: 'relative', left: -20 }}
data={data}
curve={shape.curveNatural}
svg={{ stroke: chartColor1, strokeWidth: 5 }}
contentInset={{ top: 20, bottom: 20 }}
showGrid={false}
numberOfTicks={0}
key={props.id}
>
But when I load more then 50 items performance of the app fall down to 10-15 fps.
I think it because of many SVG's on page. Which solution do you think should I use to avoid this?
I answered a similar question recently here: Real-time data update chart in React Native and will suggest the same here.
I've struggled with performance when plotting in React Native with all of the SVG-based libraries I've tried. I recently decided to try using a couple canvas-based plotting libraries within a WebView and had very good results. I ended up making a simple package: https://www.npmjs.com/package/#dpwiese/react-native-canvas-charts.
Should you not want to use this package and instead do it yourself, it's quite straightforward. While the package source code is probably the best resource I'll summarize the steps below:
Create an HTML file and import it into your component:
const htmlTemplate = require("./index.html");
where the HTML contains the JavaScript for the charting library of choice. The linked package above currently supports Chart.js v3 and uPlot. In the steps below I'll show a Chart.js configuration.
Create a ref, for example let webref.
Create a WebView and onLoadEnd you can inject some JavaScript into the WebView that will configure and create your chart
<WebView
originWhitelist={["*"]}
ref={r => (webref = r)}
source={htmlTemplate}
onLoadEnd={() => { addChart(config) }}
/>
where addChart looks something like:
const addChart = config => {
webref.injectJavaScript(`const el = document.createElement("canvas");
document.body.appendChild(el);
window.canvasLine = new Chart(el.getContext('2d'), ${JSON.stringify(config)});`);
};
and config is a valid Chart.js configuration.
To update the chart data simply inject some JavaScript to update the data. In the case of Chart.js here, that'd look like:
const setData = dataSets => {
if (dataSets) {
dataSets.forEach((_, i) => {
webref.injectJavaScript(`window.canvasLine.config.data.datasets[${i}].data = ${JSON.stringify(dataSets[i])};
window.canvasLine.update();`);
});
}
};
where dataSets are valid Chart.js data sets.
That's it! I've only played around with these two plotting libraries via the https://www.npmjs.com/package/#dpwiese/react-native-canvas-charts package, but so far performance has been really good, even with the JSON stringification of all the passed chart data. I haven't quantified it thoroughly, but both libraries are orders of magnitude more performant than any of the SVG-based ones I've tried.

How to capture an animated View as video

I am using a react-native Image to show some images from some url on the web. Now, based on some condition I update the image urls in different interval.
I want to capture this whole transition into a video file. However, I cannot find a suitable android APIs (for native side) or react-native packages to achieve that.
I already did something similer to convert an android View into a Bitmap and then encode it into a jpeg image.
A basic example of what I already have is as follows:
componentDidMount() {
setInterval(() => {
this.setState({imgUrl: 'some new url' });
}, 2000);
}
render() {
return {
<View style={styles.mystyle}><Image source={this.state.imgUrl}><View>
}
}
Please help me out here. Thanks in advance.
This could help : https://github.com/ycswaves/react-native-screen-recorder
I've not tried this myself, just came across while doing a google search
Possible duplicate question : Is there any plugins for recording screen and voice in React Native with iOS

How to get list of local videos and display them in grid format in React Native?

I am trying to do something similar to what Instagram has for their select video screen. Where a grid of local videos that can be uploaded and it'll kind of 'preview' the one that is currently selected above the grid itself.
I'm using the react-native-community/cameraroll and this is the code I'm trying to get the Videos with.
CameraRoll.getPhotos({first: 20, assetType: "All"})
.then(r => this.setState({ videos: r.edges }))
.catch((err) => {
console.log('getVideosErr:' + err)
})
and I am trying to display the grid with some sample code I found and tried playing around with:
<ScrollView>
{this.state.videos.map((p, i) => {
return (
<Video
key={i}
style={{
width: 300,
height: 100,
}}
source={{ uri: p.node.video.uri }}
/>
;
})}
I have one video on the simulator but I am getting an error saying "TypeError: Cannot read property 'uri' of undefined" everytime I try grabbing the video.
Not so sure what the issue is right now, I followed the samples on the documentation for the cameraroll but haven't had any luck yet. Any advice/examples would be appreciated.
Use react-native-media-helper
implementation:
import MediaHelper from 'react-native-media-helper'
<MediaHelper
numVideos={20} // for android
media='Videos' // for ios
num={20} // for ios
onCancel={() => this.setState({visible: false})}
onSelectedItem={(item) => alert(JSON.stringify(item))}
/>

How to speed up initial launch app of React native and Expo app

I have created an app and added splach screen. It takes 1 second to load the app on Android Emulator. However after I publish the app in the store, it takes 4 seconds to load.
This is pretty annoying for such a simple app.
I was thinking it was because of _loadResourcesAsync func to load pictures. Therefore I commented out those lines but nothing has changed.
Any recommendation to speed up my app launch.
Here you can find my app.js
import React from 'react';
import { Platform, StatusBar, StyleSheet, View } from 'react-native';
import { AppLoading, Asset } from 'expo';
import AppNavigator from './navigation/AppNavigator';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoadingComplete: false,
};
}
render() {
if (!this.state.isLoadingComplete && !this.props.skipLoadingScreen) {
return (
<AppLoading
startAsync={this._loadResourcesAsync}
onError={this._handleLoadingError}
onFinish={this._handleFinishLoading}
/>
);
} else {
return (
<View style={styles.container}>
{Platform.OS === 'ios' && <StatusBar barStyle="default" />}
<AppNavigator />
</View>
);
}
}
_loadResourcesAsync = async () => {
return Promise.all([
Asset.loadAsync([
// require('./assets/images/big_bottle.png'),
// require('./assets/images/bottle.png'),
// require('./assets/images/coffee.png'),
// require('./assets/images/juice.png'),
// require('./assets/images/menu.png'),
// require('./assets/images/tea.png'),
// require('./assets/images/water-glass.png'),
]),
]);
};
_handleLoadingError = error => {
// In this case, you might want to report the error to your error
// reporting service, for example Sentry
console.warn(error);
};
_handleFinishLoading = () => {
this.setState({ isLoadingComplete: true });
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
});
Based on my experience, hybrid apps, in general, tend to launch slower.
Based on my tests, even a completely blank Expo app, based on the device performance, can take anywhere from 1-4s to launch. This is the time it takes from the moment the user taps (opens) the app to the time the splash screen gets hidden (and the first app screen is visible).
What you can do to speed it up is a really broad topic. Here are two recommendations, that helped a lot for a project of mine:
Cashe your assets.
Bundling assets into your binary will provide for the best user experience as your assets will be available immediately. Instead of having to make a network request to the CDN to fetch your published assets, your app will fetch them from the local disk resulting in a faster, more efficient loading experience.
Always load a cached version of your app first.
You can configure the "updates" section in your app.json to always starts with the cached version of your app first (fallbackToCacheTimeout: 0) and continue trying to fetch the update in the background (at which point it will be saved into the cache for the next app load).
Unfortunately, as of today, it looks like we're kind of limited to what we can do to improve further the initial loading time on a blank app. There isn't really a reliable way to know how long the 'check for updates' process takes, the general React Native initialization time, the 'load all the JS' time.
There is a feature request for tools for improving the startup time, would be great if the Expo team introduces something similar anytime in the future.

Downloading data files with React Native for offline use

I am wanting to develop an app where a user can select different gamepacks to install on their android or ios device. A gamepack will consist of:
one or more JSON files
images
sounds
Right now I'm not really concerned if these are transferred individually or in a zip file (though a zip file would certainly be preferred). Of course the device will need to be connected to the Internet to get the current list of gamepacks and to download the ones that the user chooses. Once the gamepacks are downloaded to the phone the user will not need an Internet connection to play the game as they will have all the files.
How do I go about implementing this in my project?
How do I download the files? Would I use the react-native-fetch-blob library and save it in a specific location? This library refers to saving it as "cache" rather than permanently, so I am not sure if this is the correct solution. The specific section I am looking at on the library page is "Use Specific File Path". But because it is cache, should I be looking for something else that is more of a longer term storage? It does say on the page that files will not be deleted so I am a bit confused as to what the difference between permanent storage and cache is in this case.
Once the files are downloaded would I then be able to open images and display them, open sound files and play them, and open the json files and process them?
Check out React Native FS, specifically the documentation on downloadFile:
https://github.com/johanneslumpe/react-native-fs#downloadfileoptions-downloadfileoptions--jobid-number-promise-promisedownloadresult-
Here's a working example:
import React, { Component } from 'react';
import {
AppRegistry,
Text,
View,
Image,
} from 'react-native';
import RNFS from 'react-native-fs';
export default class downloadFile extends Component {
constructor() {
super()
this.state = {
isDone: false,
};
this.onDownloadImagePress = this.onDownloadImagePress.bind(this);
}
onDownloadImagePress() {
RNFS.downloadFile({
fromUrl: 'https://facebook.github.io/react-native/img/header_logo.png',
toFile: `${RNFS.DocumentDirectoryPath}/react-native.png`,
}).promise.then((r) => {
this.setState({ isDone: true })
});
}
render() {
const preview = this.state.isDone ? (<View>
<Image style={{
width: 100,
height: 100,
backgroundColor: 'black',
}}
source={{
uri: `file://${RNFS.DocumentDirectoryPath}/react-native.png`,
scale: 1
}}
/>
<Text>{`file://${RNFS.DocumentDirectoryPath}/react-native.png`}</Text>
</View>
) : null;
return (
<View>
<Text onPress={this.onDownloadImagePress}>Download Image</Text>
{preview}
</View>
);
}
}
AppRegistry.registerComponent('downloadFile', () => downloadFile);
It's important to know that the height and width must be set on the Image

Categories

Resources