Flatlist Does Not Appear - Nested Flatlists - reactjs

I am attempting to nest a Flatlist. I am using two Realm object arrays and need to conditionally display items from the "ingredients" array based on a value within the "inventories" array.
I am wondering if I have my "return statements" placed incorrectly or whether my logic is skewed. Please advise. Any help would be much appreciated. Thank you.
import * as React from 'react';
import {View, Text, FlatList} from "react-native";
import realm from '../schemas/InventoryDatabase';
export default class ViewInventory extends React.Component {
constructor(props) {
super(props);
this.state = {
FlatListInventoryItems: [],
};
this.state = {
FlatListIngredientItems: [],
};
var inventories = Object.values(realm.objects('Inventories'));
var ingredients = Object.values(realm.objects('Ingredients'));
this.state = {
FlatListInventoryItems: inventories,
};
this.state = {
FlatListIngredientItems: ingredients,
};
}
ListViewItemSeparator = () => {
return (
<View style={{ height: 0.5, width: '100%', backgroundColor: '#000' }} />
);
};
render() {
return (
<View>
<FlatList
data={this.state.FlatListInventoryItems}
ItemSeparatorComponent={this.ListViewItemSeparator}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item }) => (
<View style={{ backgroundColor: 'white', padding: 20 }}>
<Text>Inventory ID: {item.recordID}</Text>
<Text>Name: {item.inventoryName}</Text>
<Text>Date: {item.date}</Text>
<FlatList
data={this.state.FlatListIngredientItems}
ItemSeparatorComponent={this.ListViewItemSeparator}
keyExtractor={(item2, index) => index.toString()}
renderItem={({ item2 }) => {
if (item2.inventoryID == item.recordID) {
return (
<View style={{ backgroundColor: 'gray', padding: 20 }}>
<Text>Ingredient ID: {item2.ingredientID}</Text>
<Text>Ingredient Type: {item2.ingredientType}</Text>
<Text>Ingredient: {item2.ingredient}</Text>
</View>
);
}
}}
/>
</View>
)}
/>
</View>
);
}
}

Everything looks ok.
However, ScrollViews should never be nested. Consider using map instead of your second FlatList.

Related

React native Tried to get frame for out of range index NaN (MYSQL database)

So I started learning react-native from videos and they have used ListView but as the ListView will be deprecated soon and will be removed. I get to know that FlatList will be the proper replacement but being a beginner I am not able to migrate to Flatlist.
Error message
ListView has been removed from React Native.See link for more information or use 'deprecated-react-native-listview'
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
FlatList,
ActivityIndicator,
} from 'react-native';
import { createStackNavigator, createAppContainer } from 'react-navigation';
export default class Login extends Component {
static navigationOptions= ({navigation}) =>({
header: null
});
state = {
username : [],
data : []
}
constructor(props) {
super(props);
this.state = {
isLoading: true, // check if json data (online) is fetching
dataSource: [], // store an object of json data
};
}
componentDidMount () {
return fetch("http://172.16.2.109:8090/assessment/getdata2.php?username=test2312")
.then((response) => response.json())
.then((responseJson) => {
// set state value
this.setState({
isLoading: false, // already loading
dataSource: responseJson
});
})
.catch((error) => {
ToastAndroid.show(error.toString(), ToastAndroid.SHORT);
});
}
render() {
const { navigate } = this.props.navigation;
if(this.state.isLoading) {
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return(
<View style={{flex: 1, paddingTop:20}}>
<FlatList
data={this.state.dataSource}
renderItem={({item}) => {
return (
<View>
<Text style={styles.info}>{item.ascendant} is </Text>
</View>
)
}}
keyExtractor={(item, index) => index.toString()}
/>
</View>
);
}
}
const styles = StyleSheet.create({
info: {
fontSize: 20,
}
});
Hope this helps!
import { FlatList } from 'react-native';
<FlatList
data={this.state.dataSource}
showsVerticalScrollIndicator={false}
renderItem={(rowData, index) => (
<Text style={styles.rowViewContainer} onPress={this.GetListViewItem.bind(this, rowData.fruit_name)}>{rowData.fruit_name}</Text>
<View
style={{
height: .5,
width: "100%",
backgroundColor: "#000",
}}
/>
)}
keyExtractor={(item, index) => index.toString()}
style={{marginTop: 10}}
/>
try this code
import { AppRegistry, StyleSheet, FlatList, Text, View, Alert, ActivityIndicator, Platform} from 'react-native';
class Project extends Component {
constructor(props)
{
super(props);
this.state = {
isLoading: true
}
}
componentDidMount() {
return fetch('https://reactnativecode.000webhostapp.com/FruitsList.php')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson
}, function() {
// In this block you can do something with new state.
});
})
.catch((error) => {
console.error(error);
});
}
FlatListItemSeparator = () => {
return (
<View
style={{
height: 1,
width: "100%",
backgroundColor: "#607D8B",
}}
/>
);
}
GetFlatListItem (fruit_name) {
Alert.alert(fruit_name);
}
render() {
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={styles.MainContainer}>
<FlatList
data={ this.state.dataSource }
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem={({item}) => <Text style={styles.FlatListItemStyle} onPress={this.GetFlatListItem.bind(this, item.fruit_name)} > {item.fruit_name} </Text>}
keyExtractor={(item, index) => index}
/>
</View>
);
}
}
const styles = StyleSheet.create({
MainContainer :{
justifyContent: 'center',
flex:1,
margin: 10,
paddingTop: (Platform.OS === 'ios') ? 20 : 0,
},
FlatListItemStyle: {
padding: 10,
fontSize: 18,
height: 44,
},
});
AppRegistry.registerComponent('Project', () => Project);

How do i navigate to a new screen from FlatList?

I would like to navigate to a screen called GridVid when clicking the items in my FlatList. I can't figure out how to do this as the
onPress={() => this.props.navigation.navigate('GridVid')}
only will work being called in App.js as thats where the StackNavigator is defined, not the ListItem class (which is in a separate file called ListItem.js)
//App.js
class SettingsClass extends Component {
constructor(props) {
super(props)
this.state = {
columns: 3, //Columns for Grid
};
}
render() {
const {columns} = this.state
return (
<View style={styles.grid}>
<FlatList
numColumns={columns}
data={[
{uri:'https://randomuser.me/api/portraits/thumb/women/12.jpg'},
{uri:'https://randomuser.me/api/portraits/thumb/women/13.jpg'},
{uri:'https://randomuser.me/api/portraits/thumb/women/14.jpg'},
]}
renderItem={({item}) => {
return (<ListItem itemWidth={(ITEM_WIDTH-(10*columns))/columns}
image={item}
/>
)
}}
keyExtractor={
(index) => { return index }
}
/>
</View>
);
}
}
//Settings Class swipes to GridVid
const SettingsStack = createStackNavigator({
SettingsScreen: {
screen: SettingsClass
},
GridVid: {
screen: GridVidClass
},
});
//ListItem.js
export default class ListItem extends Component {
state = {
animatepress: new Animated.Value(1)
}
animateIn() {
Animated.timing(this.state.animatepress, {
toValue: 0.90,
duration: 200
}).start()
}
animateOut() {
Animated.timing(this.state.animatepress, {
toValue: 1,
duration: 200
}).start()
}
render() {
const {itemWidth} = this.props
return (
<TouchableWithoutFeedback
onPressIn={() => this.animateIn()}
onPressOut={() => this.animateOut()}
onPress={() => this.props.navigation.navigate('GridVid')} //WONT WORK HERE in this file!!!!
>
<Animated.View style={{
margin:5,
transform: [{scale: this.state.animatepress}] }}>
<Image style={{width:itemWidth, height: 100}} source={this.props.image}></Image>
</Animated.View>
</TouchableWithoutFeedback>
);
}
}
//GridVid.js
export default class GridVidClass extends Component {
render() {
return (
<View style={styles.container}>
<Text>On GridVid </Text>
</View>
);
}
}
Is there any way to call onPress={() => this.props.navigation.navigate('GridVid') within the FlatList (or anywhere in App.js) as opposed to ListItem (where it wont work at the moment)? In ListItem however, at least i'm clicking the image that i want and have some reference to what i'm clicking.
What you need to do is pass a onPress prop to your ListItem that will make the navigation happen.
//App.js
class SettingsClass extends Component {
constructor(props) {
super(props)
this.state = {
columns: 3, //Columns for Grid
};
}
render() {
const {columns} = this.state
return (
<View style={styles.grid}>
<FlatList
numColumns={columns}
data={[
{uri:'https://randomuser.me/api/portraits/thumb/women/12.jpg'},
{uri:'https://randomuser.me/api/portraits/thumb/women/13.jpg'},
{uri:'https://randomuser.me/api/portraits/thumb/women/14.jpg'},
]}
renderItem={({item}) => {
return (<ListItem itemWidth={(ITEM_WIDTH-(10*columns))/columns}
image={item}
onPress={() => this.props.navigation.navigate('GridVid') // passing the onPress prop
/>
)
}}
keyExtractor={
(index) => { return index }
}
/>
</View>
);
}
}
//Settings Class swipes to GridVid
const SettingsStack = createStackNavigator({
SettingsScreen: {
screen: SettingsClass
},
GridVid: {
screen: GridVidClass
},
});
//ListItem.js
export default class ListItem extends Component {
state = {
animatepress: new Animated.Value(1)
}
animateIn() {
Animated.timing(this.state.animatepress, {
toValue: 0.90,
duration: 200
}).start()
}
animateOut() {
Animated.timing(this.state.animatepress, {
toValue: 1,
duration: 200
}).start()
}
render() {
const {itemWidth} = this.props
return (
<TouchableWithoutFeedback
onPressIn={() => this.animateIn()}
onPressOut={() => this.animateOut()}
onPress={this.props.onPress} // using onPress prop to navigate
>
<Animated.View style={{
margin:5,
transform: [{scale: this.state.animatepress}] }}>
<Image style={{width:itemWidth, height: 100}} source={this.props.image}></Image>
</Animated.View>
</TouchableWithoutFeedback>
);
}
}
ListItem is not in StackNavigator so it doesn't know what navigation is
You can go with like Vencovsky's answer or pass navigation prop from ListItem's parent component
<ListItem
itemWidth={(ITEM_WIDTH-(10*columns))/columns}
image={item}
navigation={this.props.navigation}
/>

React Native TouchableOpacity OnPress not Working with loop

I have a scrollview in which multiple items are generated with loop. I added TouchableOpacity above these items because i want these objects to be touchable. But when i add a method on onPress method it shows error not a function , is undefined
List_Data Component:
class List_Data extends React.Component {
fetchData = () => {
console.log("DONE");
}
_renderView = () => {
return (
<View style={{flex:1, padding: 20}}>
<View style={styles.container}>
<ScrollView horizontal={true} showsHorizontalScrollIndicator={false} >
{
this.state.Data.map(function (data, index) {
return (
<TouchableOpacity key={index} onPress={() => this.fetchData()}>
<Image source={{uri: data.imageSrc}}
resizeMode={'cover'}
style={{width: '100%', height: imageHeight}}
/>
</TouchableOpacity>
);
})
}
</ScrollView>
</View>
</View>
)
}
render() {
return (
{this._renderView()}
);
}
}
I don't know whats the issue, it just a method which prints on console.
The issue is coming from your .map. Basically you are losing the value of this as you are not using an arrow function. If you change your .map(function(data, index) to .map((data,index) => it should work.
import * as React from 'react';
import { Text, View, StyleSheet, ScrollView, TouchableOpacity, Image } from 'react-native';
import { Constants } from 'expo';
export default class App extends React.Component {
state = {
Data: [
{imageSrc :'https://randomuser.me/api/portraits/men/39.jpg'},
{imageSrc: 'https://randomuser.me/api/portraits/women/38.jpg'},
{imageSrc: 'https://randomuser.me/api/portraits/men/37.jpg'},
{imageSrc: 'https://randomuser.me/api/portraits/women/36.jpg'},
{imageSrc: 'https://randomuser.me/api/portraits/men/35.jpg'},
{imageSrc: 'https://randomuser.me/api/portraits/women/34.jpg'},
]
}
// let's pass something so that we know that it is working
fetchData = (index) => {
alert(`you pressed ${index}`)
}
_renderView = () => {
return (
<View style={{flex: 1, padding: 20}}>
<View style={styles.container}>
<ScrollView horizontal={true} showsHorizontalScrollIndicator={false} >
{
this.state.Data.map((data, index) => { // change this to an arrow function
return (
<TouchableOpacity key={index} onPress={() => this.fetchData(index)}>
<Image source={{uri: data.imageSrc}}
resizeMode={'cover'}
style={{width: 100, height: 100}}
/>
</TouchableOpacity>
);
})
}
</ScrollView>
</View>
</View>
);
}
render() {
return (
this._renderView()
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
}
});
You can see it working in the following snack https://snack.expo.io/#andypandy/map-with-arrow-function
Try keyboardShouldPersistTaps={true} under ScrollView. <ScrollView keyboardShouldPersistTaps={true}>

Can't use react-native-snap-carousel

I would like use react-native-snap-carousel but when I try to init in I have an error :(
the exemple :
import Carousel from 'react-native-snap-carousel';
export class MyCarousel extends Component {
_renderItem ({item, index}) {
return (
<View style={styles.slide}>
<Text style={styles.title}>{ item.title }</Text>
</View>
);
}
render () {
return (
<Carousel
ref={(c) => { this._carousel = c; }}
data={this.state.entries}
renderItem={this._renderItem}
sliderWidth={sliderWidth}
itemWidth={itemWidth}
/>
);
}}
My code :
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Carousel from 'react-native-snap-carousel';
export default class App extends React.Component {
_renderItem ({item, index}) {
return (
<View style={styles.slide}>
<Text style={styles.title}>{ item.title }</Text>
</View>
);}
render () {
return (
<Carousel
ref={(c) => { this._carousel = c; }}
data={this.state.entries}
renderItem={this._renderItem}
sliderWidth={150}
itemWidth={100}
/>
);
}}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
}});
Screenshot
the same on app.js react Native
I'have see a issue (the same like me)
link to Github Issue
But not answer and issue be close
As the screenshot says, this.state.entries is null.
You must initialize it :
export default class App extends React.Component {
constructor() {
super()
this.state = {
entries: [],
}
}
_renderItem ({item, index}) {
return (
<View style={styles.slide}>
<Text style={styles.title}>{ item.title }</Text>
</View>
);}
render () {
return (
<Carousel
ref={(c) => { this._carousel = c; }}
data={this.state.entries}
renderItem={this._renderItem}
sliderWidth={150}
itemWidth={100}
/>
);
}}
In this example, entries: [] wont display anything since there's no object in it. You can initialize it with wanted data:
entries: [
{ title: 'hello' },
{ title: 'world' },
]
Btw, this issue has nothing to do with the plugin itself, even if they could catch it.

How to stop React-Native FlatList Interfering with other components

I have a simple React-Native app that uses FlatList with Redux. The problem is that when the list becomes long and reaches the bottom of the screen where the input elements exists it disrupts these input elements even though they are in another component and container. I've tried a million fixes for this, but nothing seems to work.
How can I do something like only have FlatList occupy 2/3rds of the screen?
This is a screenshot of the issue (when the items reach the input boxes it results in the input boxes shrinking and being disrupted):
This is the app file that contains all my components:
export default class App extends Component {
render() {
return (
<Provider store={createStore(reducers)}>
<View style={{ flex: 1 }}>
<ItemsList />
<AddItem />
</View>
</Provider>
);
}
}
This is the component that uses FlatList:
class ItemsList extends Component {
render() {
return (
<List>
<FlatList
data={this.props.items}
renderItem={({ item }) => (
<ListItem
name={item.item} id={item.id}
/>
)}
keyExtractor={item => item.id.toString() }
/>
</List>
);
}
}
const mapStateToProps = state => {
return { items: state.items };
};
export default connect(mapStateToProps)(ItemsList);
The code for addItem is:
class AddItem extends Component {
state = {
item: "",
quantity: ""
}
onButtonPress() {
this.props.addItem(this.state)
this.setState({
item: "",
quantity: 0
})
}
render() {
const { input, container, add, addText } = styles;
return (
<View style={container}>
<TextInput placeholder="add item"
placeholderTextColor="rgba(0, 0, 0, 0.5)"
style={input}
onChangeText={item => this.setState({ item })}
value={this.state.item}
/>
<TextInput placeholder="add item"
placeholderTextColor="rgba(0, 0, 0, 0.5)"
style={input}
onChangeText={quantity => this.setState({ quantity })}
/>
<TouchableOpacity style={add} onPress={this.onButtonPress.bind(this)}>
<Text style={addText}>Add Item</Text>
</TouchableOpacity>
</View>
);
}
}
export default connect(null, {addItem})(AddItem);
const styles = {
input: {
backgroundColor: 'rgb(208, 240, 238)',
paddingVertical: 15,
paddingHorizontal: 10,
marginBottom: 5
},
add: {
backgroundColor: 'black',
paddingVertical: 15,
},
addText: {
textAlign: 'center',
color: 'white'
},
container: {
padding: 20,
flex: 1,
justifyContent: 'flex-end'
}
};
First of all, remove <List> from your ItemsList since you already use FlatList. Then, for your FlatList to take up 2/3 of the screen height do this:
class ItemsList extends Component {
render() {
return (
<View style={{ flex: 2 }}>
<FlatList
data={this.props.items}
renderItem={({ item }) => (
<ListItem
name={item.item} id={item.id}
/>
)}
keyExtractor={item => item.id.toString() }
/>
</View>
);
}
}
const mapStateToProps = state => {
return { items: state.items };
};
export default connect(mapStateToProps)(ItemsList);

Resources