React Native FlatList not scrolling within flexbox UI - javascript

I have spent hours trying to understand why my flat list refuses to scroll. I have see many solutions about adding "flexGrow: 1" to the contentContainerStyle prop of the list, sadly that doesnt solve for me here. I have tried many variations of using flex/flexGrow: 1 in the style prop too, but still no scrolling. I attach what my code for this page looks like:
import React, { Component } from "react";
import { Dimensions, FlatList, View, StyleSheet, TouchableOpacity } from "react-native";
import { Button, Block, Text } from "galio-framework";
import Theme from "../../constants/Theme";
import { StatusBar } from "expo-status-bar";
import MapView, { PROVIDER_GOOGLE } from "react-native-maps";
import SvgCarIcon from "../../components/SvgCarIcon";
import DashIcons from "../../components/DashIcons";
export default class MakePayment extends Component {
constructor(props) {
super(props);
this.state = {
source: {
latitude: 0,
longitude: 0,
latitudeDelta: 0.005,
longitudeDelta: 0.005
},
rideOptions: [
{
title: "Ride A",
passengers: 4,
arrivalTime: "10:00 - 10:07 arrival",
price: "5.00",
isSelected: false
},
{
title: "Ride B",
passengers: 7,
arrivalTime: "10:00 - 10:07 arrival",
price: "7.50",
isSelected: false
},
{
title: "Ride C",
passengers: 6,
arrivalTime: "12:00 - 13:30 arrival",
price: "3.50",
isSelected: false
}
]
};
}
toggleOption = (INDEX) => {
let updatedRideOptions = this.state.rideOptions.slice().map((item, index) => {
INDEX === index ? item["isSelected"] = !item["isSelected"] : item["isSelected"] = false
return item;
})
this.setState({rideOptions: updatedRideOptions}, () => console.log(this.state.rideOptions));
}
componentDidMount() {
let { lat, lng } = this.props.route.params.source.geometry.location;
this.setState({
source: {
...this.state.source,
latitude: lat,
longitude: lng
}
}, () => console.log(this.state.source));
}
render() {
return (
<View style={styles.container}>
<StatusBar hidden/>
<MapView
provider={PROVIDER_GOOGLE}
showsCompass={true}
showsUserLocation={true}
style={styles.map}
initialRegion={{
latitude: 37.78825,
longitude: -122.4324,
latitudeDelta: 0.0922,
longitudeDelta: 0.0421
}}
region={this.state.source}
/>
<View style={styles.menuContainer}>
<Text style={styles.header}>Time To Pick A Dash!</Text>
<FlatList
contentContainerStyle={{
width: "90%",
flexGrow: 1,
alignItems: "center",
borderColor: "red",
borderStyle: "solid",
borderWidth: 2
}}
scrollEnabled={true}
keyExtractor={((item, index) => String(index))}
data={this.state.rideOptions}
renderItem={({ item , index}) => {
return (
<TouchableOpacity
activeOpacity={0.9}
style={[styles.dashRideBox, item.isSelected && styles.btnSelected]}
onPress={() => this.toggleOption(index)}
>
<SvgCarIcon color={item.isSelected ? Theme.COLOURS.WHITE : Theme.COLOURS.SECONDARY}/>
<Block style={{ paddingRight: 25 }}>
<Text size={18} color={item.isSelected ? Theme.COLOURS.WHITE : Theme.COLOURS.SECONDARY}>{item.title}
<Text small style={item.isSelected && styles.textSelected}>{item.passengers}</Text>
</Text>
<Text size={14} style={item.isSelected ? styles.textSelected : styles.subText}>{item.arrivalTime}</Text>
</Block>
<Text color={item.isSelected ? Theme.COLOURS.WHITE : Theme.COLOURS.SECONDARY} size={24}>{item.price}</Text>
</TouchableOpacity>
);
}}
/>
</View>
<Block style={styles.paymentContainer}>
<Block style={{
flex: 0.4, flexDirection: "row", alignItems: "center"
}}>
<Block style={styles.card}>
<DashIcons name={"visa"} size={40}/>
<Text size={14} color={Theme.COLOURS.SUB_TEXT} bold>VISA ***** 4700</Text>
<TouchableOpacity
style={{
flex: 1,
alignItems: "center"
}}
onPress={() => console.log("Card drop down opened...")}
>
<DashIcons name={"dropdown-arrow"} size={14} color={"grey"}/>
</TouchableOpacity>
</Block>
<Button style={styles.recent}>
<DashIcons name={"clock"} size={22}/>
</Button>
</Block>
<Button style={styles.confirmBtn} color={"#F2F2F2"}>
<Text size={24} color={Theme.COLOURS.SECONDARY}>Confirm your dash</Text>
</Button>
</Block>
</View>
);
}
}
const { width: WIDTH } = Dimensions.get("window"); //Max Width of phone screen
const { height: HEIGHT } = Dimensions.get("window");
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
fontFamily: "Roboto",
backgroundColor: Theme.COLOURS.WHITE
},
menuContainer: {
flex: 0.3,
justifyContent: "space-between",
alignItems: "center",
width: "100%",
paddingHorizontal: 10,
elevation: 1
},
dashRideBox: {
flexGrow: 0.475,
backgroundColor: Theme.COLOURS.WHITE,
width: "100%",
paddingHorizontal: 5,
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
borderRadius: 10,
elevation: 3,
shadowRadius: 10
},
map: {
flex: 0.45,
width: WIDTH
},
paymentContainer: {
marginTop: 10,
flex: 0.25,
paddingHorizontal: 10,
justifyContent: "center",
alignItems: "center",
borderStyle: "solid",
borderWidth: 2,
borderColor: "rgba(0,0,0,0.1)"
},
header: {
fontWeight: "bold",
fontSize: 18,
color: Theme.COLOURS.SUB_HEADER,
paddingVertical: 10
},
subText: {
color: Theme.COLOURS.SUB_TEXT
},
card: {
flex: 0.7,
height: 45,
flexDirection: "row",
justifyContent: "flex-start",
alignItems: "center",
borderRadius: 30,
backgroundColor: Theme.COLOURS.WHITE,
elevation: 5,
paddingLeft: 10
},
recent: {
flex: 0.3,
borderRadius: 30,
backgroundColor: Theme.COLOURS.WHITE,
elevation: 5,
},
confirmBtn: {
flex: 0.6,
width: 343,
borderRadius: 30,
elevation: 3
},
btnSelected: {
backgroundColor: Theme.COLOURS.BUTTON
},
textSelected: {
color: Theme.COLOURS.WHITE
}
})
Any advice as to why the list doesn't scroll?
Link to expo snack to see current state: Expo Snack

Related

React-native-Agenda how to add a new item to the Agenda

I'm trying to add values ​​through the Modal inputs and I'm able to save and print these values, but I need to add them to the Agenda.
The Agenda asks for an object and even though I created an object, the Agenda says that it is either an array or a string and does not accept the type in the prop items.
What would be the function that will print correctly in the Agenda?
My code:
import React, { useEffect, useState } from 'react'
import { StyleSheet, View, Text, TouchableOpacity, Modal, TextInput, Alert } from 'react-native'
import { LocaleConfig, Agenda } from 'react-native-calendars'
import DateTimePicker from 'react-native-modal-datetime-picker';
import { Feather } from '#expo/vector-icons';
import { Ionicons } from '#expo/vector-icons';
import { Fontisto } from '#expo/vector-icons';
LocaleConfig.locales['tr'] = {
monthNames: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio" ,"Junho" ,"Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"],
monthNamesShort: ["Jan", "Fev", "Mar", "Abr", "Mai", "Jun", "Jul", "Ago", "Set", "Out", "Nov", "Dez"],
today: "Hoje",
dayNames: ["Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado", "Domingo"],
dayNamesShort: ["Seg", "Ter", "Qua", "Qui", "Sex", "Sáb", "Dom"]
}
LocaleConfig.defaultLocale = "tr"
const Calendario = () => {
const [modalVisible, setModalVisible] = useState(false);
// informações que serão adicionadas ao calendário
const [events, setEvents] = useState(null);
const [dateSelected, setDateSelected] = useState('');
const [description, setDescription] = useState({});
const [refreshCalender, setRefreshCalender] = useState(false);
const item = {
data: "2022-07-26",
title: "teste",
description: "teste"
}
const renderItem = (item) => {
return(
<View style={styles.itemContainer}>
<Text>{item.title}</Text>
<Text>{item.description}</Text>
</View>
)
}
const [isDatePickerVisible, setDatePickerVisibility] = useState(false);
const showDatePicker = () => {
setDatePickerVisibility(true);
};
const hideDatePicker = () => {
setDatePickerVisibility(false);
};
const handleConfirm = (date) => {
console.log("A date has been picked: ", date);
setDateSelected(date);
hideDatePicker();
};
return (
<>
<Agenda
items={item}
renderEmptyDate={() => {
return <View />;
}}
renderEmptyData={() => {
return <View />;
}}
selected={new Date()}
minDate={null}
renderItem={renderItem}
markingType="custom"
refreshing={refreshCalender}
/>
<View>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert('Modal has been closed.');
setModalVisible(!modalVisible);
}}>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalText}>Adicione um horário</Text>
<TextInput
placeholder='Título'
onChangeText={(text) => setEvents(text)}
style={styles.input}
/>
<TextInput
placeholder='Descrição'
onChangeText={(text) => setDescription(text)}
style={styles.input}
/>
<TouchableOpacity
style={styles.btnDatePicker}
onPress={showDatePicker}
>
<Text>Selecionar data</Text>
<Fontisto name="date" size={20} color="#fff" style={{ margin: 10 }} />
</TouchableOpacity>
<DateTimePicker
mode='date'
minimumDate={null}
isVisible={isDatePickerVisible}
onConfirm={handleConfirm}
onCancel={hideDatePicker}
/>
<TouchableOpacity
style={[styles.button2, styles.buttonClose2]}
onPress={() => {
console.log(events)
console.log(description)
console.log(dateSelected)
console.log(typeof(dateSelected))
setModalVisible(false)
}}>
<Text style={styles.textStyle}>
<Ionicons name="checkmark-sharp" size={24} color="black" />
</Text>
</TouchableOpacity>
<TouchableOpacity
style={[styles.button, styles.buttonClose]}
onPress={() => setModalVisible(!modalVisible)}>
<Text style={styles.textStyle}>
<Feather name="x-circle" size={24} color="black" />
</Text>
</TouchableOpacity>
</View>
</View>
</Modal>
<TouchableOpacity style={styles.btn}
onPress={() => setModalVisible(true)}
>
<Ionicons name={'add-outline'} size={30} color={'black'}/>
</TouchableOpacity>
</View>
</>
)
}
export default Calendario
const styles = StyleSheet.create({
itemContainer: {
backgroundColor: "#fff",
margin: 5,
borderRadius: 15,
justifyContent: "center",
alignItems: "center",
flex: 1,
},
centeredView: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
marginTop: 22,
},
modalView: {
margin: 20,
backgroundColor: 'white',
borderRadius: 20,
width: "90%",
height: "60%",
alignItems: 'center',
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 2,
},
shadowOpacity: 0.25,
shadowRadius: 4,
elevation: 5,
},
button: {
borderRadius: 20,
padding: 10,
elevation: 2,
position: "absolute",
right: 0,
bottom: 0,
margin: 15,
},
button2: {
borderRadius: 20,
padding: 10,
elevation: 2,
position: "absolute",
left: 0,
bottom: 0,
margin: 15,
},
buttonOpen: {
backgroundColor: '#F194FF',
},
buttonClose: {
backgroundColor: 'red',
},
buttonClose2: {
backgroundColor: '#9beb34',
},
textStyle: {
color: 'white',
fontWeight: 'bold',
textAlign: 'center',
},
modalText: {
marginBottom: 15,
textAlign: 'center',
fontWeight: "bold",
fontSize: 24,
margin: 10
},
btn: {
position: "absolute",
right: 0,
bottom: 0,
backgroundColor: "#0782F9",
padding: 10,
borderRadius: 30,
alignItems: "center",
margin: 15
},
input: {
width: "90%",
backgroundColor: "white",
paddingHorizontal: 15,
paddingVertical: 10,
borderRadius: 10,
marginTop: 5,
borderBottomWidth: 2,
borderBottomColor: "#313131"
},
dateComponent: {
width: "60%",
marginTop: 20,
marginBottom: 5,
},
btnDatePicker: {
padding: 15,
marginHorizontal: 10,
alignItems: "center",
backgroundColor: "#0782F9",
marginTop: 20,
width: "40%",
borderRadius: 15,
},
});
As per library mention you item is object and this object contains a key as a date and this key contain array so you item data look like
const item = {
"2022-07-26":[{name:"teste",description: "teste"}]
}
return (
<>
<Agenda
items={item}
renderEmptyDate={() => {
return <View />;
}}
renderEmptyData={() => {
return <View />;
}}
selected={new Date()}
minDate={null}
renderItem={renderItem}
markingType="custom"
refreshing={refreshCalender}
/>
</>
)
}
export default Calendario

How to create the attached UI(grid with different squares) in react native?

Here's the UI I want to create:
How do I create the above UI in react native and have it scale on all devices? I tried using flexbox but I couldn't get the boxes to be squares. The code below is using fixed width and height in which I was thinking I could scale them in proportion to the flex container they're in but I don't know how that would be implemented and I haven't found anything similar so far.
return (
<View>
<View style={styles.cardContainer}>
<View style={styles.leftSection}></View>
<View style={styles.rightSection}>
<View style={styles.section}>
<View style={styles.smallSquare}></View>
<View style={styles.smallSquare}></View>
<View style={styles.smallSquare}></View>
</View>
<View style={styles.section}>
<View style={styles.smallSquare}></View>
<View style={styles.smallSquare}></View>
<View style={styles.smallSquare}></View>
</View>
</View>
</View>
</View>
);
}
const styles = StyleSheet.create({
cardContainer: {
height: 152,
flexDirection: "row",
borderRadius: 26,
marginTop: 8,
padding: 5,
backgroundColor: "lightgrey",
justifyContent: "space-between",
},
leftSection: {
flex: 3,
backgroundColor: "teal",
borderRadius: 23,
},
rightSection: {
flex: 5,
marginHorizontal: 10,
},
largeSquare: {
width: "100%",
height: "100%",
borderRadius: 23,
},
section: {
flex: 1,
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
},
smallSquare: {
backgroundColor: "teal",
borderRadius: 14,
width: 62,
height: 62,
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.5.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.5.0/umd/react-dom.production.min.js"></script>
I just made the code for you. Just copy and play with it.
import React from "react";
import { FlatList, StyleSheet, Text, View } from "react-native";
const DATA = [1, 2, 3, 4, 5, 6];
const renderItem = ({ item }) => {
return <View style={styles.item}></View>;
};
function App() {
return (
<View style={styles.app}>
<View style={styles.letConatiner} />
<View style={{ flex: 2.5 }}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={(item) => item}
numColumns={3}
/>
</View>
</View>
);
}
const styles = StyleSheet.create({
app: {
flex: 1,
flexDirection: "row",
flexWrap: "wrap",
backgroundColor: "lightgrey",
padding: 10
},
letConatiner: {
height: "62%",
flex: 1,
backgroundColor: "teal",
borderRadius: 15,
marginTop: 10
},
item: {
flex: 1,
padding: 50,
backgroundColor: "green",
margin: 10,
borderRadius: 15,
height: "50%"
}
});
export default App;
Not the perfect solution I was hoping to find but it's a start. Maybe someone can build on it.
import { StatusBar } from "expo-status-bar";
import {
StyleSheet,
View,
Text,
Image,
Pressable,
FlatList,
Dimensions,
} from "react-native";
const windowWidth = Dimensions.get("window").width;
const windowHeight = Dimensions.get("window").height;
export default function HomeScreen() {
return (
<View style={styles.homeScreen}>
<View style={styles.cardOuter}>
<View style={styles.cardContainer}>
<View style={styles.leftSection}>
<View style={styles.bigThumbnail}></View>
</View>
<View style={styles.rightSection}>
<View style={styles.section}>
<View style={styles.smallThumbnail}></View>
<View style={styles.smallThumbnail}></View>
<View style={styles.smallThumbnail}></View>
</View>
<View style={styles.section}>
<View style={styles.smallThumbnail}></View>
<View style={styles.smallThumbnail}></View>
<View style={styles.smallThumbnail}></View>
</View>
</View>
</View>
</View>
</View>
);
}
const styles = StyleSheet.create({
homeScreen: {
backgroundColor: "black",
flex: 1,
paddingHorizontal: 10,
},
cardOuter: {
paddingVertical: 4,
backgroundColor: "#eee",
borderRadius: 26,
},
cardContainer: {
height: windowHeight / 5.4,
flexDirection: "row",
borderRadius: 26,
paddingHorizontal: 10,
justifyContent: "center",
alignItems: "center",
},
leftSection: {
marginRight: 0,
},
rightSection: {
flex: 5,
},
bigThumbnail: {
backgroundColor: "teal",
borderRadius: 26,
width: windowWidth / 3,
height: "96%",
},
smallThumbnail: {
backgroundColor: "teal",
borderRadius: 14,
width: windowWidth / 6,
height: windowWidth / 6,
},
section: {
flex: 1,
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
paddingLeft: 10,
marginVertical: 0,
},
});

horizontal ScrollView is not scrolling

When adding horizontal={true} to my scrollview, I thought that would be enough to be able to scroll sideways. For some reason, even though there is enough content to scroll to, the images will not scroll continuously. If you copy and paste this code into snack.expo.io you will see what I mean.
I am not sure what is causing this issue, as I know the normal scrollview vertically works fine and scrolls like normal. I have also tried using nestedScrollenabled to true
Any insight at all is appreciated more than you know!
import React, { useState } from 'react';
import {Pressable, StyleSheet, Text, View, useWindowDimensions, Dimensions, Image, Animated, PanResponder,
TouchableOpacity, ScrollView, ImageBackground, Platform} from 'react-native';
import { SearchBar } from 'react-native-elements';
import {
scale,
verticalScale,
moderateScale,
ScaledSheet,
} from 'react-native-size-matters';
import { MaterialCommunityIcons } from '#expo/vector-icons';
const Images = [
{ id: '1', uri: require('./assets/snack-icon.png'), text: 'Test' },
{ id: '2', uri: require('./assets/snack-icon.png') /*text: "Test"*/ },
{ id: '3', uri: require('./assets/snack-icon.png') /*text: "Test"*/ },
{ id: '4', uri: require('./assets/snack-icon.png') /*text: "Test"*/ },
]
const pressableTest = () => {
let textlog = '';
const [state, setState] = useState(0);
};
export default class Home extends React.Component {
renderImagesHorizontal = () => {
return Images.map((item, i) => {
return (
<View
style={{
width : '150%',
paddingLeft: scale(10),
paddingRight: scale(10),
paddingBottom: scale(15),
}}>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('VenueDetails')}>
<ImageBackground
source={item.uri}
style={{
width: '100%',
height: scale(225),
shadowColor: '#000',
shadowOffset: { width: 1, height: 4 },
shadowOpacity: 1,
}}
imageStyle={{ borderRadius: 10 }}>
<View
style={{
position: 'absolute',
bottom: 10,
left: 10,
justifyContent: 'flex-start',
alignItems: 'flex-start',
}}>
<Text style={styles.name}>Name</Text>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Text style={styles.category}>Category</Text>
<Text style={styles.dot}>⬤</Text>
<Text style={styles.money}>$$</Text>
<Text style={styles.dot}>⬤</Text>
<Text style={styles.starRating}>★★★</Text>
</View>
</View>
</ImageBackground>
</TouchableOpacity>
</View>
);
});
};
renderImagesVertical = () => {
return Images.map((item, i) => {
return (
<View style={{ paddingLeft: scale(10), paddingRight: scale(10), paddingBottom: scale(20) }}>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('VenueDetails')}>
<ImageBackground
source={item.uri}
style={{ width:'100%', height: scale(125),
shadowColor: '#000',
shadowOffset: {width: 1, height: 7},
shadowOpacity: 1,}} imageStyle = {{ borderRadius: 20}}>
<View
style={{
position: 'absolute',
bottom: 10,
left: 10,
justifyContent: 'flex-start',
alignItems: 'flex-start',
}}>
<Text style={styles.name}>Name</Text>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Text style={styles.category}>Category</Text>
<Text style={styles.dot}>⬤</Text>
<Text style={styles.money}>$$</Text>
<Text style={styles.dot}>⬤</Text>
<Text style={styles.starRating}>★★★</Text>
</View>
</View>
</ImageBackground>
</TouchableOpacity>
</View>
);
});
};
state = {
search: '',
};
updateSearch = (search) => {
this.setState({ search });
};
render() {
const { search } = this.state;
return (
<ScrollView style={{ flex: 1, backgroundColor: '#272933', horizontal: 'true' }}>
<View style={{flexDirection:'row', marginTop: scale(20)}}>
{/*this will proabbly say somethign different and probably have a different look to it but you get the idea
I was also trying to add a shadow to this but couldnt figure it out. */}
<Text style={{marginTop: scale(30) ,fontSize: scale(40), fontWeight: 'bold', color: '#FFFFFF', paddingLeft: scale(20)}}>
Home
</Text>
<View style={{paddingTop: scale(40), paddingLeft: scale(155)}}>
</View>
</View>
<SearchBar
placeholder="Search..."
onChangeText={this.updateSearch}
value={search}
round='true'
containerStyle={{backgroundColor: '#272933', borderBottomColor: 'transparent', borderTopColor: 'transparent',
paddingLeft: scale(20) , paddingRight: scale(20)}}
inputContainerStyle={{height: scale(30), width: scale(310), backgroundColor: '#3A3B3C'}}
searchIcon={() => <MaterialCommunityIcons name="glass-mug-variant" size={25} color='#87909A'/>}
clearIcon= 'null'
/>
<ScrollView
horizontal={true}
>
<View style={{ flex: 1, flexDirection : 'row', marginTop: 15 }}>{this.renderImagesHorizontal()}</View>
</ScrollView>
<View style={{ flex: 1, marginTop: 15 }}>{this.renderImagesVertical()}</View>
</ScrollView>
);
}
}
const styles = ScaledSheet.create({
starRating: {
color: 'white',
fontSize: '20#s',
textShadowOffset: { width: 2, height: 2 },
textShadowRadius: 2,
textShadowColor: '#000',
},
category: {
color: 'white',
fontSize: '20#s',
textShadowOffset: { width: 2, height: 2 },
textShadowRadius: 2,
textShadowColor: '#000',
},
name: {
fontWeight: 'bold',
color: 'white',
fontSize: '25#s',
textShadowOffset: { width: 2, height: 2 },
textShadowRadius: 2,
textShadowColor: '#000',
},
dot: {
color: 'white',
fontSize: '5#s',
paddingLeft: '5#s',
paddingRight: '5#s',
textShadowOffset: { width: 2, height: 2 },
textShadowRadius: 2,
textShadowColor: '#000',
},
money: {
color: 'white',
fontSize: '20#s',
},
});
in android you must add nestedScrollEnabled={true} to Enables nested scrolling for Android API level 21+. see here
<ScrollView>
<ScrollView nestedScrollEnabled={true}>
</ScrollView>
</ScrollView>
try snack here (test in android & ios not web)

React Native app works on iOS but comes up with error on Android posts.map not defined

I have created a simple program to display information from my website on the app. It works on iOS but on my Android device an error shows up :
posts.map is not a function. This is my code:
import React, { Component } from 'react';
import {
View,
Text,
ActivityIndicator,
ScrollView,
StyleSheet,
Image,
Header,
} from 'react-native';
let lw = 100;
import Img from 'react-image';
let li = 'https://www.teanewsnetwork.com/profileicons/';
let bean = 'azure.jpg';
export default class App extends Component {
state = {
loading: true,
error: false,
posts: [],
};
componentWillMount = async () => {
try {
const response = await fetch(
'https://www.teanewsnetwork.com/api/fetcharticles.php?code=#NIL7*GKD60JTRTEFZ0CkvpHMJJW^-9q&starting=0&limit=40'
);
const posts = await response.json();
this.setState({ loading: false, posts });
} catch (e) {
this.setState({ loading: false, error: true });
}
};
renderPost = ({ id, title, content, authorimage, authorname }, i) => {
let b = { authorname };
return (
<View style={styles.postContent}>
<View
style={{
flex: 1,
flexDirection: 'column',
textAlign: 'center',
justifyContent: 'center',
alignItems: 'center',
}}>
<Text style={styles.postauthor}>{title} </Text>
<Image
source={{
uri: `https://teanewsnetwork.com/profileicons/${authorimage}`,
}}
defaultSource={require('./contact-outline.png')}
style={{
width: lw,
height: lw,
flex: 1,
justifyContent: 'center',
alignItems: 'center',
borderRadius: lw / 2,
}}
/>
<Text style={styles.postauthor}>{authorname}</Text>
</View>
<Text style={styles.postBody}>{content}</Text>
</View>
);
};
render() {
const {posts, loading, error} = this.state
if (loading) {
return (
<View style={styles.center}>
<ActivityIndicator animating={true} />
</View>
)
}
if (error) {
return (
<View style={styles.center}>
<Text>
Failed to load posts!
</Text>
</View>
)
}
return (
<ScrollView style={styles.container}>
{posts.map(this.renderPost)}
</ScrollView>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
borderBottomWidth: 0,
borderBottomColor: 'red',
top: 100,
zIndex: 6,
},
postauthor: {
flex: 1,
borderBottomWidth: 0,
borderBottomColor: 'red',
paddingVertical: 25,
fontSize: 18,
paddingRight: 15,
left: 10,
justifyContent: 'center',
alignItems: 'center',
textAlign: 'center',
},
postContent: {
flex: 1,
borderBottomWidth: 20,
borderBottomColor: '#EEE',
borderRadius: 4,
fontSize: 18,
left: 0,
paddingRight: 15,
justifyContent: 'center',
alignItems: 'center',
textAlignVertical: 'center',
textAlign: 'center',
},
postBody: {
marginTop: 1,
fontSize: 18,
color: 'black',
left: 10,
textAlign: 'center',
},
center: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
I am a beginner coder on react native and would like to have some help here. The code works on iOS emulator with EXPO but doesnt work on my Android Device.
Thanks in Advance!
Most likely posts is not a array, check the type of posts.

Take picture, save and access Camera with react-native

I am studing react-native a 4 months and I am Build my App. I got problems with Camera. I am trying to take a picture, save and access the photo. I take a picture but I don't know where picture goes and how to acess.
I am using expo import camera, because when I use from react a get some error.
this is my code:
import React, {Component} from 'react';
import {Text, View, TouchableOpacity, Image,TouchableHighlight,Vibration} from 'react-native';
//import Camera from 'react-native-camera';
import {Camera, Permissions,} from 'expo';
const myStyle = {
container: {
flex: 1,
flexDirection: 'row',
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center'
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
color: 'red',
padding: 10,
margin: 40
},
main2: {
flex: 1,
//alignItems: 'flex-start',
flexDirection: 'row',
justifyContent: 'space-between',
},
main: {
flex: 1,
},
borda: {
//flex: 0.1,
alignItems: 'flex-end',
backgroundColor: 'black',
height: 110,
},
borda2: {
backgroundColor: 'black',
width: 60,
},
borda3: {
width: 60,
backgroundColor: 'black',
},
borda4: {
height: 120,
backgroundColor: 'black',
//flex: 1,
alignItems: 'center',
flexDirection: 'row',
justifyContent:'space-between',
},
texto:{
fontSize: 18,
marginBottom: 40,
color: 'white',
},
textoButton:{
fontSize: 18,
color: 'white',
marginTop: 5,
},
button:{
alignSelf: 'flex-end',
alignItems: 'center',
backgroundColor:'transparent',
flexDirection: 'row',
justifyContent:'space-between'
},
cameraStyle:{
width: 70,
height: 57,
//margin:30,
alignItems: 'center',
tintColor: 'white',
},
flipStyle:{
width: 52,
height: 57,
marginLeft:10,
alignItems: 'center',
tintColor: 'white',
},
gallerystyle:{
width: 64,
height: 57,
marginLeft:10,
alignItems: 'center',
tintColor: 'white',
marginRight: 10,
},
closeStyle:{
width: 56,
height: 57,
marginTop: 30,
marginRight: 20,
alignItems: 'flex-end',
tintColor: 'white',
justifyContent:'flex-end'
},
box:{
width: 'auto',
justifyContent: 'space-between',
flexDirection: 'column',
alignItems: 'center',
},
};
export default class CameraAcess extends Component {
constructor(props) {
super(props);
this.state = {hasCameraPermission: null, type: Camera.Constants.Type.back,};
}
async componentWillMount() {
const {status} = await Permissions.askAsync(Permissions.CAMERA);
this.setState({hasCameraPermission: status === 'granted'});
}
snap = async function(){
if (this.camera) {
this.camera.takePictureAsync().then(data => {
FileSystem.moveAsync({
from: data,
to: '${FileSystem.documentDirectory}photos/Photo_${this.state .photoId}.jpg',
}).then(() => {
this.setState({
photoId: this.state.photoId + 1,
});
Vibration.vibrate();
})
.catch((e) => {
console.log(e, 'ERROR');
});
})
.catch((e) => {
console.log(e, 'takePicture ERROR');
});
}
console.log('I took the picture');
};
cameraPhoto = require('./Images/camera.png');
flipPhoto = require('./Images/flip.png');
closePhoto = require('./Images/close.png');
galleryPhoto = require('./Images/gallery.png');
render() {
const { main,main2, borda, borda2, borda3,borda4,cameraStyle,flipStyle,closeStyle,box,textoButton,gallerystyle} = myStyle;
const {hasCameraPermission} = this.state;
if (hasCameraPermission === null) {
return <View/>;
} else if (hasCameraPermission === false) {
return <Text>No access to camera</Text>;
} else {
return (
<View style={main}>
<Camera style={main} type={this.state.type}>
<TouchableHighlight onPress={() => {this.props.navigator.push({id: 'MenuPrincipal'});}}
style={borda} underlayColor={'black'} activeOpacity={0.6}>
<Image source={this.closePhoto} style={[closeStyle]}/>
</TouchableHighlight>
<View style={main2}>
<View style={[borda2]}/>
<View style={[borda3]}/>
</View>
<View style={[borda4]}>
<TouchableOpacity onPress={() => {this.setState({type: this.state.type === Camera.Constants.Type.back
? Camera.Constants.Type.front : Camera.Constants.Type.back,});}}>
<View style={box}>
<Image source={this.flipPhoto} style={[flipStyle]}/>
<Text style={textoButton}>
Flip
</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={() => {this.snap()}}>
<View style={box}>
<Image source={this.cameraPhoto} style={[cameraStyle]}/>
<Text style={textoButton}>
Capture
</Text>
</View>
</TouchableOpacity>
<TouchableOpacity onPress={() => {false}}>
<View style={box}>
<Image source={this.galleryPhoto} style={[gallerystyle]}/>
<Text style={textoButton}>
Gallery
</Text>
</View>
</TouchableOpacity>
</View>
</Camera>
</View>
);
}
}
}
Someone help me to solve this problem and please be especific and clearly in your explanation, every details are necessary to me. I need this to end my App.
If I were you I would do
console.log(data);
then you can see what the promise returns in the XDE. You should, at the very least, see the following properties: height, width, uri. Uri will show you exactly where that image is being stored in the cache.

Categories