data from firebase not mapped react native - javascript

i have data from firebase and i want map it to my custom panels but it seems not mapped (my panels do not show up) but when i console log it, the data succesfully retreived. here is my code
constructor(props) {
super(props);
this.state ={
requests:[]
}
}
componentDidMount(){
this.fetchRequests();
}
fetchRequests(){
this.subscriber = firebase.firestore()
.collection("requests").onSnapshot(docs => {
let requests = []
docs.forEach(doc => {
requests.push(doc.data())
})
this.setState({requests})
})
}
buildPanels() {
this.state.requests.map((req, idx) => {
return <View key={idx} style={styles.panel}>
<View style={{flex: 1}}>
<View style={styles.panelRow}>
<Text style={styles.panelText}>Nama Resipien</Text>
<Text style={styles.panelText}>{req.name}</Text>
</View>
<View style={styles.panelRow}>
<Text style={styles.panelText}>Golongan Darah</Text>
<Text style={{flex: 0.5}}>{req.golDarah}</Text>
</View>
</View>
</View>
})
render(){
return(
<View style={styles.container}>
<ScrollView>
{this.buildPanels()}
</ScrollView>
</View>
);
}

Add return method in your code like
buildPanels() {
return this.state.requests.map((req, idx) => {
return <View key={idx} style={styles.panel}>
<View style={{flex: 1}}>
<View style={styles.panelRow}>
<Text style={styles.panelText}>Nama Resipien</Text>
<Text style={styles.panelText}>{req.name}</Text>
</View>
<View style={styles.panelRow}>
<Text style={styles.panelText}>Golongan Darah</Text>
<Text style={{flex: 0.5}}>{req.golDarah}</Text>
</View>
</View>
</View>
})

Related

How to make Flatlist render Text,View elements? in rn

How to make Flatlist render Text, View elements? In rn, I am currently using scroll view, but I want to test flatlist I read rn docs to know about it, but I can't render text view elements with their styles, Can anyone tell how to do that in a proper way? I just want to use flatlist instead of scroll view
Elements that I want to render:
<View style={styles.section1}>
<Image style={styles.profileimg} source={{ uri: data.profilepic }} />
<Text style={styles.usernameText}>#{data.username}</Text>
<View style={styles.Postrow}>
<View style={styles.Postrow1}>
<Text style={styles.followerTxt}>UpVotes</Text>
<Text style={styles.UpVote}>{data.upvotes}</Text>
</View>
<View style={styles.verticalLine}></View>
<View style={styles.Postrow1}>
<Text style={styles.followerTxt}>DownVotes</Text>
<Text style={styles.UpVote}>{data.downvotes}</Text>
</View>
<View style={styles.verticalLine}></View>
<View style={styles.Postrow1}>
<Text style={styles.followerTxt}>Posts</Text>
<Text style={styles.UpVote}>{data.post.length}</Text>
</View>
</View>
<Text style={styles.decs}>Hello this is des</Text>
</View>
<View style={styles.section1}>
<Text style={styles.postTxt}>Your Posts</Text>
<View style={styles.posts}>
{
data.post.map((item) => {
return (
<Image key={item.id} style={styles.Postimage} source={{ uri: item.postimg }} />
)
})
}
</View>
</View>
you need to use the renderItem prop with FlatList
first create function component to pass it to the renderItem prop:
const renderItem = (item) => (
<View style={styles.section1}>
<Image style={styles.profileimg} source={{ uri: data.profilepic }} />
<Text style={styles.usernameText}>#{data.username}</Text>
<View style={styles.Postrow}>
<View style={styles.Postrow1}>
<Text style={styles.followerTxt}>UpVotes</Text>
<Text style={styles.UpVote}>{data.upvotes}</Text>
</View>
<View style={styles.verticalLine}></View>
<View style={styles.Postrow1}>
<Text style={styles.followerTxt}>DownVotes</Text>
<Text style={styles.UpVote}>{data.downvotes}</Text>
</View>
<View style={styles.verticalLine}></View>
<View style={styles.Postrow1}>
<Text style={styles.followerTxt}>Posts</Text>
<Text style={styles.UpVote}>{data.post.length}</Text>
</View>
</View>
<Text style={styles.decs}>Hello this is des</Text>
</View>
<View style={styles.section1}>
<Text style={styles.postTxt}>Your Posts</Text>
<View style={styles.posts}>
{
data.post.map((item) => {
return (
<Image key={item.id} style={styles.Postimage} source={{ uri: item.postimg }} />
)
})
}
</View>
</View>
)
the in your screen call the flatlist:
<FlatList
data={/*here pass your data*/}
keyExtractor={(item, index) => index.toString()} // use index better than using item.id
renderItem={renderItem}
nestedScrollEnabled={true}
/>
You can Use Below Code :-
const renderItem=({item,index})=>{
return(
<View style={styles.section1}>
<Image style={styles.profileimg} source={{
uri:item.profilepic}} />
<Text style={styles.usernameText}>#{item.username}</Text>
<View style={styles.Postrow}>
<View style={styles.Postrow1}>
<Text style={styles.followerTxt}>UpVotes</Text>
<Text style={styles.UpVote}>{item.upvotes}</Text>
</View>
<View style={styles.verticalLine}></View>
<View style={styles.Postrow1}>
<Text style={styles.followerTxt}>DownVotes</Text>
<Text style={styles.UpVote}>{item.downvotes}</Text>
</View>
<View style={styles.verticalLine}></View>
<View style={styles.Postrow1}>
<Text style={styles.followerTxt}>Posts</Text>
<Text style={styles.UpVote}>{item.post.length}</Text>
</View>
</View>
<Text style={styles.decs}>Hello this is des</Text>
</View>
<View style={styles.section1}>
<Text style={styles.postTxt}>Your Posts</Text>
<View style={styles.posts}>
{
item.post.map((item) => {
return (
<Image key={item.id} style={styles.Postimage} source={{ uri: item.postimg }} />
)
})
}
</View>
</View>
)
}
<FlatList
data={your_data}
keyExtractor={item=>item.id}
renderItem={renderItem}
/>

Flat List Data is not showing

I am using flatlist for show user input notes in my app. But Flat List is not render any item that i entered. I used static list for testing and it works correctly. but when i enter a text through textinput it is not showing.
const addToDoHandler = () => {
if(userInput == ''){
return;
}
const newTodo = {
id: Math.floor(Math.random() * 1000),
text: userInput,
completed: false,
};
const newTodos = [...todos, newTodo];
setTodos(newTodos);
//clear user input
setUserInput('');
};
const renderItem = ( {item} ) => {
<View style={{backgroundColor:'#6b4d87', marginVertical: 10, flexDirection:'row', alignItems:'center', justifyContent:'space-between', height:60, width:'95%', borderRadius:10 }}>
<View>
<Text style={{color:'black', fontSize:20, fontWeight:'bold'}}>{item.text}</Text>
</View>
<TouchableOpacity onPress={() => deleteHandler(item.id)}>
<TrashIcon size={35} name="trash" style={{color:'#eff9f0'}} />
</TouchableOpacity>
</View>
};
return (
<SafeAreaView style={styles.root}>
<View style={styles.txtInputView}>
<TextInput
value={userInput}
onChangeText={text => setUserInput(text)}
style={styles.textInput}
placeholder={"Enter Your Note..."}
/>
<TouchableOpacity style={styles.addButton} onPress={addToDoHandler}>
<PlusSign size={35} name="add-sharp" style={styles.plusIcon}/>
</TouchableOpacity>
</View>
<View style={{alignItems:'center'}}>
<FlatList
data={todos}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
</View>
</SafeAreaView>
);
You need to return the components from renderItem.
Change it to:
const renderItem = ( {item} ) => (
<View style={{backgroundColor:'#6b4d87', marginVertical: 10, flexDirection:'row', alignItems:'center', justifyContent:'space-between', height:60, width:'95%', borderRadius:10 }}>
<View>
<Text style={{color:'black', fontSize:20, fontWeight:'bold'}}>{item.text}</Text>
</View>
<TouchableOpacity onPress={() => deleteHandler(item.id)}>
<TrashIcon size={35} name="trash" style={{color:'#eff9f0'}} />
</TouchableOpacity>
</View>
);

flatlist and scrollView is not working properly

I'm new in react-native. On one of my screen I'm using flatlist on 4 places but the last flatlist which is displaying at the bottom of screen is not scrolling so I add the scrollView then its working fine but displaying me that error
VirtualizedLists should never be nested inside plain ScrollViews with the same orientation because it can break windowing and other functionality - use another VirtualizedList-backed container instead.
code
const Header = () => {
return (
<View>
<SafeAreaView>
<View style={styles.sellersheaderWrapper}>
<View style={styles.sellersheaderTitle}>
<Text style={styles.sellersheaderTitleText}>
Featured Sellers
</Text>
</View>
<View>
{
isFeatureSeller == '' ?
<View style={[styles.noSpecialOfferCard, {paddingVertical:hp('2%')}]} >
<Text style={[styles.noSpecialOfferCardText, {fontSize:hp('2%')}]}>Currently, No Feature Sellers</Text>
</View>
:
<View>
<FlatList
data={isFeatureSeller}
renderItem={renderCategoryItem}
keyExtractor={item => item.id}
horizontal={true}
showsHorizontalScrollIndicator={false}
/>
</View>
}
</View>
</View>
</SafeAreaView>
<View style={styles.searchWrapper}>
<View style={styles.dobregisterFormWrapperText}>
<TextInput
style={styles.dobregisterInputStyleText}
value={search}
onChangeText={(text) => searchFilterFunction(text)}
onClear={(text) => searchFilterFunction('')}
placeholder="Search ..."
/>
<View>
<SearchIconSvg />
</View>
</View>
</View>
</View>
);
};
const Footer = () => {
return (
<View>
<View style={styles.specialOfferCardWrapper}>
<View style={styles.specialOfferCardTextWrapper}>
<Text style={styles.specialOfferCardText}>Special Offer Cards</Text>
</View>
{isSpecialCards == '' ? (
<View style={styles.noSpecialOfferCard}>
<Text style={styles.noSpecialOfferCardText}>
No Special Offer cards
</Text>
</View>
) : (
<FlatList
data={isSpecialCards}
renderItem={renderCards}
keyExtractor={(item, index) => index.toString()}
horizontal={true}
showsHorizontalScrollIndicator={false}
style={styles.specialCards}
/>
)}
<View
style={[
styles.specialOfferCardTextWrapper,
{paddingBottom: isFeatureSeller == '' ? hp('17%') :hp('10%') },
]}>
<Text style={styles.specialOfferCardText}>Cards</Text>
<FlatList
data={isCard}
renderItem={renderNormalCards}
keyExtractor={item => item.id}
showsVerticalScrollIndicator={false}
scrollEnable={true}
/>
</View>
</View>
</View>
);
};
const MainData = () => {
return(
<View>
{search == '' ? (
<ScrollView>
<View >
<Header />
<Footer />
</View>
</ScrollView>
) : (
<View >
<FlatList
data={filteredDataSource}
renderItem={renderCategoryItemSearch}
keyExtractor={(item, index) => index.toString()}
ListHeaderComponent={Header}
/>
</View>
)}
</View>
)
}
return (
<View style={styles.container}>
{
loading == true ?
<View style={{marginVertical:hp('45%')}} >
<ActivityIndicator size="large" color={colors.primary} />
</View>
:
<MainData/>
}
<View style={styles.bottomNavWrapper}>
<TouchableOpacity
style={styles.storeWrapper}
onPress={() => navigation.navigate('BuyerDashboard')}>
<View style={styles.storeIcon}>
<DashboardReverseSvg />
</View>
</TouchableOpacity>
<View style={styles.dashboardWrapper}>
<View style={styles.dashboardIcon}>
<BuyerStoreReverseSvg />
</View>
<View style={styles.dashboardText}>
<Text style={styles.dashboardTextfont}>Storefront</Text>
</View>
</View>
</View>
</View>
);
};
export default Store;
I want to scroll at here.
<ScrollView>
<View >
<Header />
<Footer />
</View>
</ScrollView>
You can use nestedScrollEnabled prop on your FlatList component
https://reactnative.dev/docs/scrollview#nestedscrollenabled

React Native - Navigation from another file

So, I'm using 2 files: The components.js where I define all parts and molds I'll use in my app, and the App.js, which has the logic and major stuff.
To sum things up, I've defined a Card class in the components.js that has a button at the end. Here is the code for the Card:
export class Card extends Component {
render() {
return (
<View style={{height: 700}}>
<View style={{flex: 8, backgroundColor: 'white', borderRadius: 20}} >
<Image source={{uri: this.props.pic}} style={styles.img}/>
<Text style={{flex: 1, fontWeight: 'bold',fontSize: 30, paddingTop: 10}}> {this.props.nome}</Text>
<Text style={{flex: 1, fontSize: 20}}> {this.props.descricao}</Text>
<TouchableHighlight style={{flex: 1}} onPress={() => ???????} underlayColor="white">
<View style={styles.button}>
<Text style={styles.buttonText}>Mais informações</Text>
</View>
</TouchableHighlight>
</View>
</View>
);
}
}
And I use it in the App.js as follows:
import {Card} from "./components.js";
class App extends Component {
render() {
return (
<View style={{flex: 1, backgroundColor:"#e6e6e1"}}>
<ScrollView>
{this.state.locations.map((pico, key) =>
<Card key={key} pic={pico.img[0]} nome= {pico.nome_do_pico} descricao={pico.how}/>
)}
</ScrollView>
</View>
);
}
}
(I've omitted the parts where it gets the info from the server and puts into the locations array)
What I need is for the button to navigate to another screen, called "Details", and I have tried a few things on the onPress but nothing has worked so far. The documentation for reactnavigation uses this.state.navigation.navigate("Details") as example, but since the Card is in another file it can't access the this.state.navigation. Any ideas?
Try if you can solve the problem by modifying the following part of your code:
in app.js
<Card key={key} pic={pico.img[0]} nome= {pico.nome_do_pico} descricao={pico.how} navigation={navigation}/>
in components.js:
<TouchableHighlight style={{flex: 1}} onPress={() => navigation.navigate('Details', {YourParameters: xx } } underlayColor="white">
<View style={styles.button}>
<Text style={styles.buttonText}>Mais informações</Text>
</View>
</TouchableHighlight>

Where to implement my function when using map for iteration?

To iterate and add views dynamically from array, I'm using following code.
export default class CreateFeedPost extends Component {
constructor(props) {
super(props);
this.state = {
selectedImages: ["1", "2", "3"]
};
}
render() {
let animation = {};
let color = Platform.OS === "android"
? styleUtils.androidSpinnerColor
: "gray";
return (
<View style={{ flex: 1, flexDirection: "column" }}>
<View style={styles.topView}>
<View style={styles.closeButtonView}>
<TouchableHighlight
underlayColor="transparent"
style={styles.closeButton}
onPress={this._closeButtonClicked.bind(this)}
>
<Icon name="times" color="#4A4A4A" size={20} />
</TouchableHighlight>
</View>
<View style={styles.postButtonView}>
<TouchableHighlight
underlayColor="transparent"
style={styles.postButton}
onPress={this._postButtonClicked.bind(this)}
>
<Text style={styles.postButtonText}>Post</Text>
</TouchableHighlight>
</View>
</View>
<View style={styles.profileContainer}>
<View style={{ width: 65, height: 65, padding: 10 }}>
<Image
source={{ uri: global.currentUser.USER_PROFILE_PIC }}
style={styles.profileImage}
/>
</View>
<View style={[styles.middleTextView]}>
<Text style={[styles.memberName]}>
{global.currentUser.USER_NAME}
</Text>
</View>
</View>
<Animated.ScrollView
style={{ flex: 1 }}
scrollEventThrottle={1}
showsVerticalScrollIndicator={false}
{...animation}
>
<View>
<TextInput
ref="postTextInputRef"
placeholder="So, What's up?"
multiline={true}
autoFocus={true}
returnKeyType="done"
blurOnSubmit={true}
style={styles.textInput}
onChangeText={text => this.setState({ text })}
value={this.state.text}
onSubmitEditing={event => {
if (event.nativeEvent.text) {
this._sendCommentToServer(event.nativeEvent.text);
this.refs.CommentTextInputRef.setNativeProps({ text: "" });
}
}}
/>
</View>
</Animated.ScrollView>
<KeyboardAvoidingView behavior="padding">
<ScrollView
ref={scrollView => {
this.scrollView = scrollView;
}}
style={styles.imagesScrollView}
horizontal={true}
directionalLockEnabled={false}
showsHorizontalScrollIndicator={false}
decelerationRate={0}
snapToInterval={100}
snapToAlignment={"start"}
contentInset={{
top: 0,
left: 0,
bottom: 0,
right: 0
}}
>
{this.state.selectedImages.map(function(name, index) {
return (
<View style={styles.imageTile} key={index}>
<View style={styles.imageView}>
<TouchableHighlight
underlayColor="transparent"
style={styles.imageRemoveButton}
onPress={() => this._imageRemoveButtonClicked.bind(this)}
>
<Icon name="times" color="#4A4A4A" size={20} />
</TouchableHighlight>
</View>
</View>
);
})}
</ScrollView>
<TouchableHighlight
underlayColor="transparent"
style={styles.cameraButton}
onPress={this._cameraButtonClicked.bind(this)}
>
<View style={styles.cameraButtonView}>
<Icon name="camera" color="#4A4A4A" size={20} />
<Text style={styles.cameraButtonText}>Add Pic</Text>
</View>
</TouchableHighlight>
</KeyboardAvoidingView>
</View>
);
}
_closeButtonClicked() {
this.props.navigator.pop();
}
_postButtonClicked() {}
_cameraButtonClicked() {
this.props.navigator.push({
title: "All Photos",
id: "photoBrowser",
params: {
limit: 3,
selectedImages: this.state.selectedImages
}
});
}
_imageRemoveButtonClicked() {
console.log("yes do it");
}
}
I'm loading code in the render method. If I write the function imageRemoveButtonClicked outside render method, it's giving an error saying that 'Cannot read property bind of undefined'. Don't know what to do. Can some one please help me in this.
Use arrow functions and class property feature. For more information about binding patterns read this article. Try to add your method as:
export class App extends Component {
yourMapFunction = () => {
yourCode...
}
}
I believe the problem is that you are not using an arrow function as the argument to this.state.selectedImages.map(). If you want to access this inside an inner function, you should use the arrow function syntax. The standard syntax does not capture this.
this.state.selectedImages.map((name, index) => {
return (...);
})

Categories