Images getting cropped with FlatList - android

The images are getting croped how can i prevent that from happening? Notice that only appears half of the image. This is a Android device. Idont know if this happens in IOS too. But a fix for android would be great
My FlatList component
import React from 'react';
import { Text, View, StyleSheet, FlatList, Image } from 'react-native';
const shows_first = [
{
key: 1,
name: 'Suits',
image: 'https://static.tvmaze.com/uploads/images/medium_portrait/0/2432.jpg'
},
{
key: 2,
name: 'Modern Family',
image: 'https://static.tvmaze.com/uploads/images/medium_portrait/0/628.jpg'
},
]
const renderItem = (item) => {
return (
<Image style={{ width: 120, height: 100 }} source={{ uri: item.image }} />
)
}
const List = () => {
return (
<View style={{ flex: 1, marginTop: 110 }}>
<FlatList
horizontal={true}
ItemSeparatorComponent={() => <View style={{ width: 5 }}></View>}
renderItem={({ item }) => renderItem(item)}
data={shows_first}
></FlatList>
</View>
)
}
export default List;

You should use a resize mode to chose how you want to display your image.
If you are sure that all your images are going to be posters better give a height and width that suits the image.
Check the code below
const renderItem = (item) => {
return (
<Image style={{ width: 80, height: 120 ,resizeMode: 'center'}} source={{ uri: item.image }} />
)
}

You will need to style your image to fit as per aspect ration so to do that you will have to add resizeMode='contain'
Working example: https://snack.expo.io/#msbot01/cranky-scones
import * as React from 'react';
import { Text, View, StyleSheet, FlatList, Image} from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import AssetExample from './components/AssetExample';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
const DATA = [
{
key: 1,
name: 'Suits',
image: 'https://static.tvmaze.com/uploads/images/medium_portrait/0/2432.jpg'
},
{
key: 2,
name: 'Modern Family',
image: 'https://static.tvmaze.com/uploads/images/medium_portrait/0/628.jpg'
}
];
export default function App() {
return (
<View style={styles.container}>
<FlatList
data={DATA}
horizontal={true}
renderItem={({ item }) =>
<View style={styles.item}>
<Image style={{ width: 120, height: 100 }} source={{ uri: item.image }} resizeMode='contain'/>
</View>
}
keyExtractor={item => item.id}
/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
paragraph: {
margin: 24,
fontSize: 18,
fontWeight: 'bold',
textAlign: 'center',
},
});

Related

Flickering components when animating the maxHeight of the ScrollView (react-native)

I have To-Do list elements which can expand and collapse by pressing the associated button.
By pressing on the EXPAND Button the height of the Animated ScrollView gets adjusted. From 0 to 100 when expanding and from 100 to 0 when collapsing. When we expand two list-objects at the same time, the screen begins to flicker.
Here the code of one single todo-element (it is abbreviated, means the DONE button is not in it):
import React, { useState, useRef, memo } from 'react';
import { Animated, Text, View, Button, ScrollView } from 'react-native';
import longText from '../data/data';
const ListObject = (props) => {
//Object Expand and Collapse feature
const expandValue = useRef(new Animated.Value(0)).current;
const [expandState, setExpand] = useState(false);
const expandAnimation = () => {
Animated.timing(expandValue, {toValue: 100, duration: 1000, useNativeDriver: false}).start();
setExpand(true);
}
const collapseAnimation = () => {
Animated.timing(expandValue, {toValue: 0, duration: 1000, useNativeDriver: false}).start();
setExpand(false);
}
return (
<View style={{ margin: props.margin }}>
<View style={{
flexDirection: 'row',
backgroundColor: 'grey',
borderRadius: 10,
}}>
<Button title='EXPAND' style={{
flex: 1,
backgroundColor: 'blue',
}}
onPress={ expandState ? collapseAnimation : expandAnimation }
/>
</View>
<Animated.ScrollView style={{
flex: 1,
paddingHorizontal: 40,
backgroundColor: 'grey',
borderRadius: 10,
maxHeight: expandValue
}}>
<Text>{ props.text }</Text>
</Animated.ScrollView>
</View>
);
}
export default memo(ListObject);
Here is the code for the App. To make a collection of all todo-elements, I map over a list and assign a key to each element:
mport React, { useRef, useState } from 'react';
import { Animated, StyleSheet, ScrollView, Text, View, SafeAreaView, Button } from 'react-native';
import longText from './src/data/data';
import ListObject from './src/components/list-object'
const styles = StyleSheet.create({
safeContainer: {
flex: 1.2
},
headerContainer: {
flex: 0.2,
flexDirection: 'column',
justifyContent: 'center',
backgroundColor: 'lightblue',
},
headerFont: {
fontSize: 50,
textAlign: 'center',
},
scrollContainer: {
flex: 1
}
});
const App = () => {
const numbers = [1,2,3,4,5,6,7,8,9];
const listItems = numbers.map((number) =>
<ListObject key={number.toString()} margin={10} headerText='I am the header of the to-do element' text={longText} />
)
return (
<SafeAreaView style={ styles.safeContainer } >
<View style={ styles.headerContainer }>
<Text style={ [styles.headerFont] }>LIST MAKER</Text>
</View>
<ScrollView style={ styles.scrollContainer }>
{listItems}
</ScrollView>
</SafeAreaView>
);
};
export default App;
I expected no flickering. The flickering appears also on my physical Android device. I have searched for similar problems and checked other libraries how they implement it.
For this, you can use react-native-collapsible
import Accordion from 'react-native-collapsible/Accordion';
const [activeSections, setActiveSessions] = useState([])
const _updateSections = (activeSections) => {
setActiveSessions(activeSections.includes(undefined) ? [] : activeSections)
}
<Accordion
sections={data}
activeSections={activeSections}
duration={400}
renderHeader={_renderHeader}
renderContent={_renderContent}
onChange={_updateSections}
touchableComponent={TouchableOpacity}
renderAsFlatList={true}
expandMultiple={true}
/>
For better performance and a smooth experience use this one.
I found the mistake by myself, it's a beginner's mistake.
Instead of managing the state of the component in the component itself, I had to lift the state up to the parent.
Here the link to the ReactJS learning doc.

How can I add a background image to my react native app?

I am fairly new to react native, but I have some experience. I am creating my own app for both ios and android by following along a tutorial that I had already completed and making my own modifications. As I was in the middle of creating an app, I forgot to add a background image. After struggling with this for several days, I'm desperate, so I decided to ask my question on here.
I am trying to add the background image to my App.js file. The image loads properly, but my page content ( which is inside <LifelineNavigator />) is either hidden or has disappeared for android. And for ios, the content seems to be in a small centered flexbox. Also, I am trying to remove the white background.
Any suggestions would definitely help. Thanks so much! God bless!
Here is my code:
import React, { useState } from "react";
import { StyleSheet, View, ImageBackground } from "react-native";
import * as Font from "expo-font";
import AppLoading from "expo-app-loading";
import { enableScreens } from "react-native-screens";
import LifelineNavigator from "./src/navigation/LifelineNavigator";
enableScreens();
const fetchFonts = () => {
return Font.loadAsync({
"Gotham-Medium": require("./src/assets/fonts/Gotham-Font/Gotham-Medium.otf")
const image = {
uri: "https://i.ibb.co/8z6QbTS/Lifeline-Gradient-Background-24.png",
};
const App = () => {
const [fontLoaded, setFontLoaded] = useState(false);
if (!fontLoaded) {
return (
<AppLoading
startAsync={fetchFonts}
onFinish={() => setFontLoaded(true)}
onError={(err) => console.log(err)}
/>
);
}
return (
<View >
<ImageBackground source={image} style={styles.image}>
<View style={ styles.container }>
<LifelineNavigator />
</View>
</ImageBackground>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
// backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
image: {
width: "100%",
height: "100%" ,
}
});
export default App;
IOS Screenshot
Android Screenshot
import React from "react";
import { ImageBackground, StyleSheet, Text, View } from "react-native";
const image = { uri: "https://reactjs.org/logo-og.png" };
const App = () => (
<View style={styles.container}>
<ImageBackground source={image} resizeMode="cover" style={styles.image}>
<Text style={styles.text}>Inside</Text>
</ImageBackground>
</View>
);
const styles = StyleSheet.create({
container: {
flex: 1,
},
image: {
flex: 1,
justifyContent: "center"
},
text: {
color: "white",
fontSize: 42,
lineHeight: 84,
fontWeight: "bold",
textAlign: "center",
backgroundColor: "#000000c0"
}
});
export default App;
follow this documentation > https://reactnative.dev/docs/imagebackground
it may solve your problem

I am facing a very mysterious problem while sending data to the Firebase database

I'm making a simple chat application with React native and Firebase. But I could not manage to send the data I wanted to add to the database with the sendMessage function. I am getting an error like this and could not find the solution. Can you help me? I couldn't find where addDoc () belongs and also I don't know what SyntheticObject means. I am having such a problem, although I do not exactly comply with what was said in the tutorial video I followed the project.
Error image:
https://i.resmim.net/i/WhatsApp-Image-2021-05-25-at-21.34.11.jpeg
Error: Function addDoc() invalid data.
import React, {useLayoutEffect, useState} from 'react'
import { TouchableOpacity } from 'react-native';
import { StyleSheet, Text, View } from 'react-native'
import {Avatar} from "react-native-elements";
import {AntDesign, FontAwesome, Ionicons} from "#expo/vector-icons";
import { SafeAreaView } from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { KeyboardAvoidingView, TextInput } from 'react-native';
import { Platform } from 'react-native';
import { ScrollView } from 'react-native';
import { Keyboard } from 'react-native';
import { TouchableWithoutFeedback } from 'react-native';
import { db, auth } from '../firebase';
import * as firebase from "firebase";
const ChatScreen = ({ navigation, route }) => {
const [input, setInput] = useState("");
useLayoutEffect(() => {
navigation.setOptions({
title: "Chat",
headerBackTitleVisible: false,
headerTitleAlign: "left",
headerTitle: () => (
<View
style={{
flexDirection: "row",
alignItems: "center",
}}>
<Avatar rounded source={{uri: "https://cencup.com/wp-content/uploads/2019/07/avatar-placeholder.png",}} />
<Text
style={{color: "white", marginLeft: 10, fontWeight: "700"}}
>{route.params.chatName}</Text>
</View>
),
headerLeft: () => (
<TouchableOpacity
style={{marginLeft: 10}}
onPress={navigation.goBack}
>
<AntDesign name="arrowleft" size={24} color="white" />
</TouchableOpacity>
),
headerRight: () => (
<View
style={{
flexDirection: "row",
justifyContent: "space-between",
width: 80,
marginRight: 20,
}}>
<TouchableOpacity>
<FontAwesome name="video-camera" size={24} color="white" />
</TouchableOpacity>
<TouchableOpacity>
<Ionicons name="call" size={24} color="white" />
</TouchableOpacity>
</View>
)
});
}, [navigation]);
const sendMessage = () => {
Keyboard.dismiss();
db.collection('chats').doc(route.params.id).collection('messages').add({
timestamp: firebase.firestore.FieldValue.serverTimestamp(),
message: input,
displayName: auth.currentUser.displayName,
email: auth.currentUser.email,
photoURL: auth.currentUser.photoURL
})
setInput('')
};
return (
<SafeAreaView style={{ flex: 1, backgroundColor: "white"}}>
<StatusBar style="light" />
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.container}
keyboardVerticalOffset={90}>
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<>
<ScrollView>
</ScrollView>
<View style={styles.footer}>
<TextInput
placeholder="Signal Message"
value={input}
onChange={text => setInput(text)}
onSubmitEditing={sendMessage}
style={styles.textInput}/>
<TouchableOpacity onPress={sendMessage} activeOpacity={0.5}>
<Ionicons name="send" size={24} color="#2B68E6" />
</TouchableOpacity>
</View>
</>
</TouchableWithoutFeedback>
</KeyboardAvoidingView>
</SafeAreaView>
)
}
export default ChatScreen
const styles = StyleSheet.create({
container: {
flex:1,
},
footer: {
flexDirection: "row",
alignItems: "center",
width: "100%",
padding: 15,
},
textInput:{
bottom: 0,
height: 40,
flex: 1,
marginRight: 15,
backgroundColor: "#ECECEC",
padding: 10,
color: "grey",
borderRadius: 30,
},
})
Error image:
https://i.resmim.net/i/WhatsApp-Image-2021-05-25-at-21.34.11.jpeg
onChange={text => setInput(text)}
While you've called the parameter "text", it's actually an event object, specifically a "SyntheticEvent" (these are event objects used by react). So later when you try to send that to the database, firebase says, basically, "uh, i can't serialize this".
Instead, you may want to use the onChangeText event:
onChangeText={text => setInput(text)}
Your onChange function should be like this
onChange={e => setInput(e.nativeEvent.text)}
You're sending the event object not the text
You could also use onChangeText prop instead
onChangeText={text => setInput(text)}

React Native: Blank space between FlatList rendered items

I'm trying to display some fetched data in app using FlatList . It works but there is a bloody big space between items!
Here is my FlatList code:
<View style={styles.showresp}>
<FlatList
data={this.state.responsjson}
renderItem={({ item }) =>
<View style={styles.weatherview}>
<Text style={styles.city}>{item.name}</Text>
<Text style={styles.country}>{item.country}</Text>
<Text style={styles.temp}>{item.temp_c}</Text>
</View>}/>
</View>
this is what i see in screen
and it is styles :
showresp: {
backgroundColor: '#fffa',
height: 315,
marginRight: '10%',
marginLeft: '10%',
marginTop: '15%',
borderRadius: 15
},
weatherview:{
alignItems: 'center',
justifyContent: 'center',
flex :1
},
city: {
fontFamily :'Wonderbar Demo',
fontSize:40,
color:'#880e4f',
},
country:{
fontSize:20,
fontFamily:'Samim-Bold',
backgroundColor:'red',
},
temp:{
fontFamily :'Wonderbar Demo',
fontSize : 40,
backgroundColor:'green',
},
I set the background color for up and down Texts to find the problem but i don't have any bloody idea about it.
could you guide me on this matter?ಠ_ಠ
I made an example for you. Look at this. The difference between you and me is no margin.
And I have my parents as a flatist.
You don't have to put View aside like this. You can put the view in the item you want.
import React, { Component } from 'react';
import { View, Text, FlatList } from 'react-native';
const users = [
{
name: 'Cathy Gilliam',
company: 'EXOVENT',
email: 'cathygilliam#exovent.com',
},
{
name: 'Norton Potts',
company: 'COREPAN',
email: 'nortonpotts#corepan.com',
},
{
name: 'Kelly Collins',
company: 'SECURIA',
email: 'kellycollins#securia.com',
},
];
export default class App extends Component {
render() {
return (
<FlatList
data={users}
renderItem={({ item }) => (
<View
style={{
borderBottomWidth: 1,
borderBottomColor: 'grey',
padding: 10
}}>
<View>
<Text style={{ fontWeight: 'bold', fontSize: 18 }}>{item.name}</Text>
<Text>{item.company}</Text>
<Text>{item.email}</Text>
</View>
</View>
)}
/>
);
}
}
It should work:
import * as React from 'react';
import { Text, View, StyleSheet, FlatList } from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import AssetExample from './components/AssetExample';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
responsjson: [{
name: 'Name1',
country: 'Country1',
temp_c: '45'
},
{
name: 'Name2',
country: 'Country2',
temp_c: '45'
}]
};
}
render() {
return (
<View style={styles.showresp}>
<FlatList
data={this.state.responsjson}
renderItem={({ item }) =>
<View style={styles.weatherview}>
<Text style={styles.city}>{item.name}</Text>
<Text style={styles.country}>{item.country}</Text>
<Text style={styles.temp}>{item.temp_c}</Text>
</View>} />
</View>
);
}
}
const styles = StyleSheet.create({
showresp: {
backgroundColor: '#fffa',
height: 315,
marginRight: '10%',
marginLeft: '10%',
marginTop: '15%',
borderRadius: 15
},
weatherview: {
alignItems: 'center',
justifyContent: 'center',
flex: 1
},
city: {
fontFamily: 'Wonderbar Demo',
fontSize: 40,
color: '#880e4f',
},
country: {
fontSize: 20,
fontFamily: 'Samim-Bold',
backgroundColor: 'red',
},
temp: {
fontFamily: 'Wonderbar Demo',
fontSize: 40,
backgroundColor: 'green',
},
});
Image:

React-Native buttons are not formatting correctly on Android

I'm using react-native-circular-action-menu for popout navigation buttons. On iPhone it looks as expected (note the circle buttons):
But on Android it's being constrained into a box:
Here is the relevant code for this component:
import React, { Component } from 'react';
import {
View,
StyleSheet,
Text,
Image,
Dimensions
} from 'react-native';
import colors from '../../../styles/colors';
import formStyles from '../../../styles/formStyles';
import ActionButton from 'react-native-circular-action-menu';
import Icon from '../../../assets/components/svgIcons.js';
import { connect } from 'react-redux';
import * as actions from '../../../actions';
import apiHelper from "../../../utils/api";
import { NavigationActions, StackNavigator } from 'react-navigation';
class ProfileCircleNav extends Component {
renderImage() {
return(
<Image
source={require("../../../assets/images/LexodyL.png")}
style={{height: 70, width: 70}}
/>
)
}
renderButton() {
if(!this.state.blocked) {
return(
<View style={{minHeight: 200, width: 350}}>
<ActionButton
buttonColor={colors.rgbaGreen}
outRangeScale={.5}
btnOutRange={colors.halfGreen}
bgColor={'transparent'}
position={"right"}
radiua={200}
icon={this.renderImage()}
onPress={this.props.onPress}
style={{zIndex: 12}}
>
<ActionButton.Item buttonColor={'transparent'} title="Request Lex" onPress={() => {this.createMeeting()}}>
<View style={styles.actionButton}>
<Icon
name='Calendar'
strokeWidth="3"
stroke={'#fff'}
fill={'#fff'}
/>
<Text style={formStyles.textStandard}>Schedule</Text>
<Text style={formStyles.textStandard}>Lex</Text>
</View>
</ActionButton.Item>
<ActionButton.Item buttonColor={'transparent'} style={styles.actionButtonIcon} title="Chat" onPress={() => this.startConvo()}>
<View style={styles.actionButton}>
<Icon
name='Chat'
strokeWidth="3"
stroke={'#fff'}
fill={'#fff'}
/>
<Text style={formStyles.textStandard}>Chat</Text>
</View>
</ActionButton.Item>
</ActionButton>
</View>
)
}
}
render() {
return (
<View style={{
bottom: Dimensions.get('window').height*.50,
backgroundColor: 'transparent',
}}>
{this.renderButton()}
</View>
);
}
}
const styles = StyleSheet.create({
actionButtonIcon: {
height: 500,
fontSize: 50,
},
actionButton: {
backgroundColor: colors.green,
height: 100,
width: 100,
borderRadius: 50,
alignItems: 'center',
justifyContent: 'center',
}
});
const mapStateToProps = (state) => {
return {
currentUser: state.currentUser
}
}
export default connect(mapStateToProps, actions)(ProfileCircleNav);
I've been trying to figure this out for hours - what am I missing here? Why is it a square on Android?
so the issue you have is that height here has no effect.
actionButtonIcon: {
height: 500,
fontSize: 50,
},
what you have to do is use the prop size to ActionButton.Item. I think a size bigger or equal than the borderRadius of 100 you are trying to apply.
<ActionButton.Item buttonColor={'transparent'} size={100} title="Request Lex" onPress={() => {this.createMeeting()}}>
Here is a working example: https://snack.expo.io/ByG7nsVwQ
You can see the prop used in the code right here

Categories

Resources