React native how to parse from json - javascript

I am trying to parse a json file with the code below and i cant get it to work, nothing is displayed.
I wanted to display some exhibits the title and their picture.
In the processExhibit i'm trying to get the json String with info and records and then map the records.
Any help is appreciated.
import React, { Component } from 'react';
import { View, Text, FlatList, Image } from 'react-native';
import PropTypes from 'prop-types';
const processExhibit = results => {
const processed = {
info: {
next: results.info.next
},
records: results.records.map(r => ({
...r,
id: r.objectnumber
}))
};
return processed;
};
class FetchExample extends Component {
constructor (props: {}) {
super(props);
this.state = {
isLoading: true,
dataSource: []
};
}
componentDidMount () {
const url =
`https://api.harvardartmuseums.org/object?apikey=83bc8170-51ae-11ea-ac7c-97706fd5f723` +
`&fields=objectnumber,dated,century,division,primaryimageurl,title` +
`&sort=totalpageviews` +
`&page=1` +
`&size=44` +
`&hasimage=1` +
`&sortorder=desc`;
fetch(url)
.then((response) => response.json())
.then((responseJson) => {
const results = processExhibit(responseJson);
this.setState({
isLoading: false,
dataSource: results
});
results = processExhibit(responseJson);
console.log("Before Change", JSON.parse(JSON.stringify(result)));
});
}
renderItem = ({item, index}) => {
let { info, records } = item;
if (!records[0]) return null;
let details = records[0];
return (
<View >
<View >
<Text >{details.title}</Text>
<Text >{details.century}</Text>
</View>
<View >
<View >
<Text >{ details.dated }</Text>
</View>
<View style={{ justifyContent: 'center', alignItems: 'center' }}>
<Image source={{uri: details.primaryimageurl}}
style={{height: 50, width: 50}}/>
</View>
</View>
</View>
);
}
keyExtractor = (item, index) => {
return index.toString();
}
render () {
return (
<View style={{flex: 1}}>
<FlatList
data={this.state.dataSource}
keyExtractor={this.keyExtractor}
renderItem={this.renderItem}
/>
</View>
);
}
}
And this is the json
info: {
next:
"https://api.harvardartmuseums.org/object?apikey=a40093f0-53ec-11ea-850a-fbf5bb8990ef&fields=objectnumber%2Cdated%2Ccentury%2Cdivision%2Cprimaryimageurl%2Ctitle&sort=totalpageviews&page=2&size=44&hasimage=1&sortorder=desc",
page: 1,
pages: 4794,
totalrecords: 210916,
totalrecordsperquery: 44
},
records: [
{
century: "19th century",
dated: "1888",
division: "European and American Art",
id: 299843,
imagepermissionlevel: 0,
objectnumber: "1951.65",
primaryimageurl: "https://nrs.harvard.edu/urn-3:HUAM:DDC251942_dynmc",
title: "Self-Portrait Dedicated to Paul Gauguin"
},
{
century: "19th century",
dated: "1877",
division: "European and American Art",
id: 228649,
imagepermissionlevel: 0,
objectnumber: "1951.53",
primaryimageurl: "https://nrs.harvard.edu/urn-3:HUAM:DDC231456_dynmc",
title: "The Gare Saint-Lazare: Arrival of a Train"
}
]
UPDATE
componentDidMount () {
const url =
`https://api.harvardartmuseums.org/object?apikey=83bc8170-51ae-11ea-ac7c-97706fd5f723` +
`&fields=objectnumber,dated,century,division,primaryimageurl,title` +
`&sort=totalpageviews` +
`&page=1` +
`&size=44` +
`&hasimage=1` +
`&sortorder=desc`;
fetch(url)
.then((response) => response.json())
.then((responseJson) => {
let results = processExhibit(responseJson);
this.setState({
isLoading: false,
dataSource: results
});
console.log("Before Change", JSON.parse(JSON.stringify(result)));
});
}
render () {
console.log('data: ', JSON.stringify(this.state.dataSource))
return (
<View style={{flex: 1}}>
<FlatList
data={[this.state.dataSource]}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
/>
</View>
);
}

Related

Implementing searchbar into flatlist to search api data react native

I've implemented an searchbar as a header of a flatlist which displays my api data (the flatlist works fine ) but the searchbar don't work , i've tried several codes but stills not working
If someone can help me with this i'll appreciate it :)
My API displays an document which contains :
-Titre(String)
-Montant(Number)
I want to search by Titre .
Here's the last code that i've tried :
class listDépenses extends React.Component{
constructor() {
super();
this.state = {
refreshing: true,
dataSource: [],
Montant:'',
Titre:'',
modalVisible:false,
loading: false,
data: [],
error: null,
}
this.arrayholder = [];
}
renderItem = ({item}) => {
<View style={{flex:1}}>
<Text style={[globalStyles.sousTitre,{marginVertical:10,marginLeft:10}]}>{item.Titre}</Text>
<Text style={[globalStyles.sousTitre,
{marginVertical:10,marginLeft:40,textAlignVertical:'auto',opacity:0.8,fontWeight:'800'}]}>
{item.Montant}</Text>
</View>}
searchFilterFunction = text => {
const newData = this.arrayholder.filter(item => {
const itemData = `${item.Titre.toUpperCase()}`;
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
renderHeader = () => {
return(
<SearchBar
placeholder="Tapez ici..."
onChangeText={text => this.searchFilterFunction(text)}
round="default"
lightTheme="default"
/>
)
}
this.setState({ data: newData });
};
async componentDidMount() {
await fetch ('http://192.168.1.10:8080/api/depenses',{
method:'get',
mode:'no-cors',
headers:{
'Accept':'application/json',
'Content-Type':'application/json'
}})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
dataSource:responseJson,
data: responseJson.results,
loading: false,
})
this.arrayholder = responseJson.results;
})
.catch((error) =>{
console.log(error)
})}
render(){
return (
<View style={{flex:1}}>
<View style={{marginBottom:10}}></View>
<FlatList
data={this.state.dataSource}
renderItem={this.renderItem}
keyExtractor={(item, index) => index}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
/>
</View>
I've found the solution if anyone need it :
class listDépenses extends React.Component{
constructor(props) {
super(props);
this.delayValue = 8000;
this.state = {
search:'',
dataSource: [],
animatedValue: new Animated.Value(0),
Montant:'',
Titre:'',
isLoading:true,
modalVisible:false,
}
this.arrayholder=[]
}
componentDidMount() {
Animated.spring(this.state.animatedValue, {
toValue: 1,
tension: 20,
useNativeDriver: true
}).start();
return fetch('http://localhost:8080/api/depenses')
.then((response )=> response.json())
.then(responseJson => {
this.setState({
dataSource: responseJson,
isLoading: false,
},
function() {
this.arrayholder = responseJson;
});})
.catch(error => { console.error(error);});}
search = text => { console.log(text);
};
clear = () => { this.search.clear();
};
SearchFilterFunction(text) {
const newData = this.arrayholder.filter(function(item) { const itemData = item.Titre
? item.Titre.toUpperCase() :
''.toUpperCase();
const textData = text.toUpperCase(); return itemData.indexOf(textData) > -1;
});
this.setState({ dataSource: newData, search: text,
});
}
render(){
if (this.state.isLoading) { return (
<View style={{ flex: 1, paddingTop: 21 }}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.container}>
<SearchBar
round="default"
lightTheme="default"
searchIcon={{ size: 25 }}
onChangeText={text => this.SearchFilterFunction(text)} onClear={text =>
this.SearchFilterFunction('')} placeholder="Tapez ici pour chercher..." value=
{this.state.search}
/>
<View style={{marginBottom:10}}></View>
<FlatList
data={this.state.dataSource}
renderItem={this.renderItem}
keyExtractor={(item, index) => index.toString()}
enableEmptySections={true} style={{ marginTop: 11 }}
ItemSeparatorComponent={this.renderSeparator}
/>
</View>

Using react-native-track-player to play selected song from flatlist

I can not figure out how I can play selected track/song from flatlist, I already had a playerscreen.js where I can play songs from my array of songs. I want to achieve users searching for songs and play the song from the selected list from the flatlist. Below is my songlist.js
const Songlist = () => {
const [loading, setLoading] = useState(false);
const navigation = useNavigation();
renderFooter = () => {
if (!loading) return null
return (
<View
style={{
paddingVertical: 20,
borderTopWidth: 1,
borderColor: '#CED0CE',
}}
>
<ActivityIndicator animating size='large' />
</View>
)
}
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: '86%',
backgroundColor: '#CED0CE',
marginLeft: '5%',
}}
/>
)
}
return (
<View>
<FlatList
data={songs}
keyExtractor={item => item.id}
renderItem={({ item, index }) => (
<TouchableOpacity
onPress={() => navigation.navigate('Player')}
>
<View
style={{
flexDirection: 'row',
padding: 16,
alignItems: 'center',
}}
>
<Avatar
source={{ uri: item.artwork.thumbnail }}
size='giant'
style={{ marginRight: 16 }}
/>
<Text
category='s1'
style={{color: '#000'}}
>{`${item.title}`}</Text>
</View>
<Text
category='s2'
style={{color: '#999', marginHorizontal: 80, bottom: 20}}
>Genre: {`${item.genre}`}</Text>
</TouchableOpacity>
)}
ItemSeparatorComponent={renderSeparator}
ListFooterComponent={renderFooter}
/>
</View>
);
}
export default Songlist;
This is my initial playerscreen.js
export default function PlayerScreen() {
const navigation = useNavigation();
const scrollX = useRef(new Animated.Value(0)).current;
const slider = useRef(null);
const isPlayerReady = useRef(false);
const index = useRef(0);
const [songIndex, setSongIndex] = useState(0);
const isItFromUser = useRef(true);
// for tranlating the album art
const position = useRef(Animated.divide(scrollX, width)).current;
const playbackState = usePlaybackState();
useEffect(() => {
// position.addListener(({ value }) => {
// console.log(value);
// });
scrollX.addListener(({value}) => {
const val = Math.round(value / width);
setSongIndex(val);
});
TrackPlayer.setupPlayer().then(async () => {
// The player is ready to be used
console.log('Player ready');
// add the array of songs in the playlist
await TrackPlayer.reset();
await TrackPlayer.add(songs);
TrackPlayer.play();
isPlayerReady.current = true;
await TrackPlayer.updateOptions({
stopWithApp: false,
alwaysPauseOnInterruption: true,
capabilities: [
Capability.Play,
Capability.Pause,
Capability.SkipToNext,
Capability.SkipToPrevious,
],
});
//add listener on track change
TrackPlayer.addEventListener(Event.PlaybackTrackChanged, async (e) => {
console.log('song ended', e);
const trackId = (await TrackPlayer.getCurrentTrack()) - 1; //get the current id
console.log('track id', trackId, 'index', index.current);
if (trackId !== index.current) {
setSongIndex(trackId);
isItFromUser.current = false;
if (trackId > index.current) {
goNext();
} else {
goPrv();
}
setTimeout(() => {
isItFromUser.current = true;
}, 200);
}
// isPlayerReady.current = true;
});
//monitor intterupt when other apps start playing music
TrackPlayer.addEventListener(Event.RemoteDuck, (e) => {
// console.log(e);
if (e.paused) {
// if pause true we need to pause the music
TrackPlayer.pause();
} else {
TrackPlayer.play();
}
});
});
return () => {
scrollX.removeAllListeners();
TrackPlayer.destroy();
// exitPlayer();
};
}, []);
// change the song when index changes
useEffect(() => {
if (isPlayerReady.current && isItFromUser.current) {
TrackPlayer.skip(songs[songIndex].id)
.then((_) => {
console.log('changed track');
})
.catch((e) => console.log('error in changing track ', e));
}
index.current = songIndex;
}, [songIndex]);
const exitPlayer = async () => {
try {
await TrackPlayer.stop();
} catch (error) {
console.error('exitPlayer', error);
}
};
const goNext = async () => {
slider.current.scrollToOffset({
offset: (index.current + 1) * width,
});
await TrackPlayer.play();
};
const goPrv = async () => {
slider.current.scrollToOffset({
offset: (index.current - 1) * width,
});
await TrackPlayer.play();
};
const renderItem = ({index, item}) => {
return (
<Animated.View
style={{
alignItems: 'center',
width: width,
transform: [
{
translateX: Animated.multiply(
Animated.add(position, -index),
-100,
),
},
],
}}>
<Animated.Image
source={item.artwork}
style={{width: 320, height: 320, borderRadius: 5}}
/>
</Animated.View>
);
};
return (
<SafeAreaView style={styles.container}>
<SafeAreaView style={{height: 320}}>
<Animated.FlatList
ref={slider}
horizontal
pagingEnabled
showsHorizontalScrollIndicator={false}
scrollEventThrottle={16}
data={songs}
renderItem={renderItem}
keyExtractor={(item) => item.id}
onScroll={Animated.event(
[{nativeEvent: {contentOffset: {x: scrollX}}}],
{useNativeDriver: true},
)}
/>
</SafeAreaView>
<TouchableOpacity
style={styles.genreContainer}
onPress={() => navigation.navigate('Genre')}
>
<SimpleLineIcons name="playlist" size={20} color='#fff' />
<Text style={styles.genre}> Genre</Text>
</TouchableOpacity>
<View>
<Text style={styles.title}>{songs[songIndex].title}</Text>
<Text style={styles.artist}>{songs[songIndex].artist}</Text>
</View>
<SliderComp />
<Controller onNext={goNext} onPrv={goPrv} />
</SafeAreaView>
);
}
import React from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text, StatusBar, ScrollView, TouchableOpacity } from 'react-native';
import Sound from 'react-native-sound';
const MusicApp = () => {
const DATA = [
{
title: 'Advertising Local',
isRequire: true,
url: require('./resource/advertising.mp3'),
},
{
title: 'Advertising URL',
url:
'https://raw.githubusercontent.com/zmxv/react-native-sound-demo/master/advertising.mp3',
},
{
title: 'Hosana',
isRequire: true,
url: require('./Hosana.mp3'),
},
{
title: 'Play aac sound from remote URL',
url:
'https://raw.githubusercontent.com/zmxv/react-native-sound-demo/master/pew2.aac',
},
{
title: 'Frog wav sound from Local',
isRequire: true,
url: require('./resource/frog.wav'),
},
{
title: 'Frog wav sound from remote URL',
url:
'https://raw.githubusercontent.com/zmxv/react-native-sound-demo/master/frog.wav',
},
];
let sound;
const playSound =(item, id)=>{
console.log("the url is "+ item.url);
if(item.url !=1){
sound = new Sound(item.url, '', (error, _sound) => {
if (error) {
alert('error' + error.message);
return;
}
stopSound
sound.play(() => {
sound.release();
});
});
}else{
sound = new Sound(item.url, (error, _sound) => {
if (error) {
alert('error' + error.message);
return;
}
stopSound
sound.play(() => {
sound.release();
});
});
}
}
const stopSound =(index)=>{
sound.stop(() => {
console.log('Stop');
});
}
const renderItem = ({ item, index }) => (
<ScrollView style={{flex: 1}}>
<View style={styles.item}>
<Text style={styles.title}> {item.title} </Text>
<TouchableOpacity onPress={()=>playSound(item, index)} style={{padding: 10, backgroundColor: 'blue'}}><Text>Play</Text></TouchableOpacity>
<TouchableOpacity onPress={()=>stopSound(index)} style={{padding: 10, backgroundColor: 'red'}}><Text>Stop</Text></TouchableOpacity>
</View>
</ScrollView>
);
return (
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: StatusBar.currentHeight || 0,
},
item: {
backgroundColor: '#f9c2ff',
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
},
title: {
fontSize: 20,
},
});
export default MusicApp;
NB:
Do yarn add react-native-sound or npm install react-native-sound.
Secondly, there are two sources of music- Remote url and local file path, ensure you modify the local file path appropriately before running

Display data from API Database with FlatList

export class Diet extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
fullData: [],
loading: false,
error: null,
query: "",
};
}
async componentDidMount() {
this.requestAPIFood();
}
requestAPIFood = _.debounce(() => {
this.setState({ loading: true });
const apiURL =
"https://api.edamam.com/api/food-database/v2/nutrients?app_id=${########}&app_key=${#######}";
fetch(apiURL)
.then((res) => res.json())
.then((resJson) => {
this.setState({
loading: false,
data: resJson,
fullData: resJson,
});
})
.catch((error) => {
this.setState({ error, loading: false });
});
}, 250);
renderFooter = () => {
if (!this.state.loading) return null;
return (
<View
style={{ paddingVertical: 20, borderTopWidth: 1, borderColor: "red" }}
>
<ActivityIndicator animating size="large" />
</View>
);
};
_renderItem = ({ item, index }) => {
return (
<TouchableOpacity style={{ height: hp("5%") }}>
<Text style={{ left: wp("1%") }}>{item.food}</Text>
</TouchableOpacity>
);
};
handleSearch = (text) => {
const data = _.filter(this.state.fullData);
this.setState({ data, query: text });
};
render() {
return (
<SearchBar
placeholder="Search Food..."
onChangeText={this.handleSearch}
value={data}
/>
<List >
<FlatList
data={this.state.data}
renderItem={this._renderItem}
keyExtractor={(item, index) => index.toString()}
ListFooterComponent={this.renderFooter}
/>
</List>
Good evening, I'm working on a SearchBar component to search food from the API database of Edamam (this is the link to the documentation: https://developer.edamam.com/food-database-api-docs) and display the result on a FlatList as you can see above, but when I start typing nothing will appear and I really can't seem to find the error.

Mapping over sent props using .map react native

i have two components one is called homeScreen the second is card i do fetch data in homeScreen i set it to state after i do send state through props to my card component .
Now my card components should generate 9 cards accoridng to the data i am sending through to it so i did map and i am getting this error
TypeError: Cannot read property '0' of undefined.
i tried to console.log props inside Card component and i could see data but for some reason the map isnt working
Card.js
const Card = props => {
Array.from({length: 9}).map((i, index) => {
console.log(props);
return (
<View style={{flex: 1}}>
<Text style={{flex: 1, backgroundColor: 'red'}}>
{props.title[1] ? `${props.title[index]}` : 'Loading'}
</Text>
<Text style={{flex: 1, backgroundColor: 'blue'}}>{props.rating[index]}</Text>
</View>
);
});
};
export default Card;
homeScreen.js
export default class HomeScreen extends React.Component {
state = {
title: [],
image: [],
rating: [],
isLoading: true,
};
componentDidMount() {
this.getData();
}
titleSend = () => {
if (!this.state.isLoading) {
{
Array.from({length: 9}).map((i, index) => {
return this.state.title[index];
});
}
}
};
imageSetter = () => {
Array.from({length: 9}).map((i, keys) => {
return (
<Image
key={keys}
style={{width: 50, height: 50, flex: 1}}
source={{uri: this.state.image[keys]}}
/>
);
});
};
getData = () => {
const requestUrls = Array.from({length: 9}).map(
(_, idx) => `http://api.tvmaze.com/shows/${idx + 1}`,
);
const handleResponse = data => {
const shows = data.map(show => show.data);
this.setState({
isLoading: false,
title: shows.map(show => show.name),
image: shows.map(show => show.image.medium),
rating: shows.map(show => show.rating.average),
});
// console.log(this.state);
};
const handleError = error => {
this.setState({
isLoading: false,
});
};
Promise.all(requestUrls.map(url => axios.get(url)))
.then(handleResponse)
.catch(handleError);
};
render() {
const {isLoading, title, image, rating} = this.state;
if (isLoading) {
return <ActivityIndicator size="large" color="#0000ff" />;
}
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<ScrollView style={{flex: 1, backgroundColor: 'red'}}>
<Card title={this.state.title} />
</ScrollView>
<Text>here images</Text>
</View>
);
}
}
None of your functions/methods using Array.from are returning a value.
For example your Card component:
const Card = props => {
// note addition of `return` statement
return Array.from({length: 9}).map((i, index) => {
console.log(props);
return (
<View style={{flex: 1}}>
<Text style={{flex: 1, backgroundColor: 'red'}}>
{props.title[1] ? `${props.title[index]}` : 'Loading'}
</Text>
<Text style={{flex: 1, backgroundColor: 'blue'}}>{props.rating[index]}</Text>
</View>
);
});
};
export default Card;
The titleSend and imageSetter methods have a similar issue.
The index error is because you're not passing an rating prop to the Card component but you're accessing props.rating[0], props.rating[1], etc.
return (
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<ScrollView style={{flex: 1, backgroundColor: 'red'}}>
// missing `rating` prop
<Card title={this.state.title} />
</ScrollView>
<Text>here images</Text>
</View>
);

How to view multiple capture image horizontally in react native?

I just want to capture image using camera API
Then Store it in array
then view one by one image horizontally in React native
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
TouchableOpacity,
Image,
PixelRatio
} from 'react-native';
import ImagePicker from 'react-native-image-picker';
let ret;
export default class Location extends Component {
constructor(props){
super(props);
this.state = {
latitude: null,
longitude: null,
address: 'address',
MyAddress: null,
error: null,
};
}
state = {
avatarSource: null,
videoSource: null
};
selectPhotoTapped() {
const options = {
quality: 1.0,
maxWidth: 500,
maxHeight: 500,
storageOptions: {
skipBackup: true
}
};
To get Image, I used this.
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled photo picker');
}
else if (response.error) {
console.log('ImagePicker Error: ', response.error);
}
else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
}
else {
let source = { uri: response.uri };
// You can also display the image using data:
//let source = { uri: 'data:image/jpeg;base64,' + response.data };
this.setState({
avatarSource: source
});
}
});
}
Then how to process to view list of image like adpater.
return (
<View style={{ flexGrow: 1, alignItems: 'center', justifyContent: 'center' }}>
To show the image in one view ,i have done this. i want to view multiple image like view pager.Like [] [] [] []
<TouchableOpacity onPress={this.selectPhotoTapped.bind(this)}>
<View style={[styles.avatar, styles.avatarContainer, {marginBottom: 20}]}>
{ this.state.avatarSource === null ? <Text>Select a Photo</Text> :
<Image style={styles.avatar} source={this.state.avatarSource} />
}
</View>
</TouchableOpacity>
</View>
)
}
}
After few hours i have done this
First save image uri in array then show in list..
let dataStorage = [{uri: response.uri}, ...this.state.dataStorage]
this.setState({dataStorage})
<FlatList
horizontal
data={this.state.dataStorage}
renderItem={({ item: rowData }) => {
return (
<View style={[styles.avatar, styles.avatarContainer, {marginBottom: 20}]}>
{ <Image style={styles.avatar} source={{uri:rowData.uri}} /> }
</View>
);
}
}
keyExtractor={(item, index) => index}
/>
Using Expo's ImagePicker this can be achieved.
Below is my code that might help you.
Note: Its performance is slow but it works.
1) state:
constructor(props) {
super(props);
this.state = {
images: []
};
}
2) openCamera function:
openCamera = async () => {
const { status } = await Permissions.askAsync(
Permissions.CAMERA,
Permissions.CAMERA_ROLL
);
this.setState({
hasCameraPermission: status === 'granted',
hasGalleryPermission: status === 'granted'
});
if (this.state.hasCameraPermission && this.state.hasGalleryPermission) {
ImagePicker.launchCameraAsync({
aspect: [1, 1],
quality: 0.2,
base64: true
})
.then(async result => {
if (!result.cancelled) {
await this.setState({
images: this.state.images.concat(result.uri)
});
Alert.alert(
'Add another picture? ',
null,
[
{
text: 'Yes',
onPress: () => this.openCamera()
},
{ text: 'No' }
],
{ cancelable: false }
);
}
console.log(this.state.images);
})
.catch(error => console.log(error));
}
};
3) To display Image:
showImages = () => {
let temp_image = [];
this.state.images.map((item, index) => {
let tempKey = item + '123';
temp_image.push(
<View key={tempKey}>
<View
key={index}
style={{
height: 100,
width: 100,
borderColor: '#dddddd'
}}
>
<Image
key={index}
source={{ uri: item }}
style={{
flex: 1,
flexDirection: 'row',
backgroundColor: 'silver',
padding: 5,
borderRadius: 5,
height: null,
width: null,
margin: 3,
resizeMode: 'cover'
}}
/>
</View>
<View key={index + 1}>
<TouchableOpacity
key={index + 2}
style={{
flex: 1,
justifyContent: 'center',
alignSelf: 'center',
width: '100%'
}}
onPress={() => {
this.removeImage(index);
this.forceUpdate();
}}
>
<Text
key={index + 3}
style={{
alignSelf: 'center',
color: '#CE3C3E',
fontWeight: 'bold'
}}
>
Delete
</Text>
</TouchableOpacity>
</View>
</View>
);
});
console.log('state images: ', this.state.images);
return temp_image;
};
4) To delete image:
removeImage = index => {
Alert.alert('Delete this image?', null, [
{
text: 'Yes',
onPress: () => {
this.state.images.splice(index, 1);
// console.log(this.state.images);
this.forceUpdate();
}
},
{ text: 'No' }
]);
};
5) And in render() function:
<ScrollView horizontal={true} style={{ flex: 1, flexDirection: 'row' }} >
{this.showImages()}
</ScrollView>

Categories

Resources