How to pass firestore data between screens React Native - javascript

I am not using classes or functions as a native component, I am using const with props as a parameter.
In my project I am using Firestore as database and I want to pass data from one screen to another and I don't know how, can someone give me some tips ?
My other problem is in the firestore query because I need to put .doc(firebase.auth().currentUser) and when I test my application an error occurs in the application.
BreadAndBounty.js
import React, { useState, useEffect } from "react";
import { View, Text, TextInput, StyleSheet, Image, ScrollView, TouchableOpacity, StatusBar, SafeAreaView, FlatList, Dimensions, ImageBackground } from 'react-native'
import { Ionicons } from '#expo/vector-icons'
import Constants from 'expo-constants'
import firebase, { firestore } from 'firebase'
require('firebase/firestore')
const { width, height } = Dimensions.get("window");
const BreadAndBounty = (props) => {
const [adverts, setAdverts] = useState([])
const getAdverts = async () => {
const querySnap = await firestore()
.collection('adverts')
.get()
const result = querySnap.docs.map(docSnap => docSnap.data())
setAdverts(result)
}
useEffect(() => {
getAdverts()
}, [])
const renderItem = (item) => {
return (
<View>
<View style={{
flexDirection: "row",
paddingTop: 50,
alignItems: "center"
}}>
<View style={{ width: "20%" }}>
</View>
<View style={{
width: "60%"
}}>
<Text style={{
fontWeight: "bold",
fontSize: 14,
color: "#044244"
}}>{item.title}</Text>
<Text style={{
fontWeight: "900",
fontSize: 12,
color: "#9ca1a2"
}}>
{item.name}
</Text>
</View>
<View style={{
width: "20%",
alignItems: "flex-end"
}}>
</View>
</View>
<TouchableOpacity
onPress={() => props.navigation.navigate(("AdvertsDetail"), { uid: firebase.auth().currentUser })}
style={{
flexDirection: "row",
width: "100%",
paddingTop: 20
}}>
<ImageBackground
source={item.image}
style={{
width: 300,
height: 220,
borderRadius: 30,
}}
imageStyle={{
borderRadius: 30,
}}
>
<View style={{
height: "100%",
flexDirection: "row",
alignItems: 'flex-end',
justifyContent: "flex-end"
}}>
</View>
</ImageBackground>
</TouchableOpacity>
</View>
)
}
return (
<ScrollView showsVerticalScrollIndicator={false}
style={{
height: "100%",
backgroundColor: "#62929E"
}}>
<View style={styles.view1}>
<View style={styles.view2}>
<View>
</View>
<View style={styles.view3}>
</View>
</View>
<Text style={styles.text1}>Bread And Bounty</Text>
<View style={styles.view_search}>
<TextInput
placeholder="Pesquisar anúncios de voluntariado..."
style={styles.textinput}>
</TextInput>
<Ionicons
name="search"
size={15}
color="#9CALA2"
></Ionicons>
</View>
</View>
<View style={styles.view4}>
<View style={{ width: "100%" }}>
<FlatList
numColumns={1}
horizontal={false}
showsVerticalScrollIndicator={false}
style={{
display: "flex",
height: Dimensions.get("screen").height,
width: Dimensions.get("screen").width
}}
data={adverts}
renderItem={({ item }) => renderItem(item)} />
</View>
</View>
</ScrollView>
)
}
export default BreadAndBounty
AdvertsDetail
import React, { useState } from 'react'
import { View, StyleSheet, Text,TouchableOpacity } from 'react-native'
import Constants from 'expo-constants';
import { Ionicons } from "#expo/vector-icons"
const AdvertsDetail = (props) => {
const [currentUser, Adverts] = useState([])
return (
<View style={styles.container}>
<View style={styles.header}>
<TouchableOpacity onPress={() => props.navigation.goBack()}>
<Ionicons name="md-arrow-back" size={24} color="#52575D"></Ionicons>
</TouchableOpacity>
</View>
<Text>{currentUser.title}</Text>
</View>
)
}
export default AdvertsDetail

We can simply access the params from the previous screen in the new screen by accessing the props of the current screen.
ex.
import React, { useState } from 'react'
import { View, StyleSheet, Text,TouchableOpacity } from 'react-native'
import Constants from 'expo-constants';
import { Ionicons } from "#expo/vector-icons"
const AdvertsDetail = (props) => {
const currentUser = props.route.params.uid
return (
<View style={styles.container}>
<View style={styles.header}>
<TouchableOpacity onPress={() => props.navigation.goBack()}>
<Ionicons name="md-arrow-back" size={24} color="#52575D"></Ionicons>
</TouchableOpacity>
</View>
<Text>{currentUser.title}</Text>
</View>
)
}
export default AdvertsDetail
Check out the official docs from react-navigation for passing the params to the screen and accessing it.
https://reactnavigation.org/docs/params/

Related

Displaying a Image from the Camera

I am relatively new to React-Native and mobile app development. I am trying to create a clone of Instagram. And in the post screen what I do is I have a button Camera and once I click on it, that should take me to CameraView screen. And in the CameraView screen I will take a picture using expo-camera and save the picture in a variable. So here, I want to export the picture and then import it in my Post screen, so that the user can have a preview of what the picture looks like before uploading. And another thing to note is that, the Post screen will by default have a Placeholder image and once the image is taken the placeholder image has to be replaced with the image.
I tried this code but it didnt work.
My Post screen :-
import { View, Text, Image, TextInput } from 'react-native';
import React, { useState, useEffect } from 'react'
import * as Yup from 'yup';
import { Formik } from 'formik'
import { Button, Divider } from 'react-native-elements';
import { useNavigation } from '#react-navigation/native';
import CameraView, { takePicture } from '../../screens/CameraView';
const PLACEHOLDER_IMG = require('../../assets/defImg.png')
const uploadPostSchema = Yup.object().shape({
caption: Yup.string().max(2200, 'Caption cannot exceed character limit.')
})
const FormikPostUploader = ({route}) => {
const [thumbnailUrl, setThumbnailUrl] = useState(PLACEHOLDER_IMG)
const navigation = useNavigation()
const handleCameraPress = () => {
UserImage = takePicture()
setThumbnailUrl(UserImage)
navigation.navigate('CameraView')
}
return (
<Formik
initialValues={{ imageUrl: '', caption:'' }}
onSubmit={(values) => console.log(values)}
validationSchema={uploadPostSchema}
validateOnMount={true}>
{({
handleBlur,
handleChange,
handleSubmit,
values,
errors,
isvalid
}) => (
<>
<View style={{ margin: 20, justifyContent: 'space-between', flexDirection: 'row' }}>
<Image source={thumbnailUrl} />
<View style={{ flex: 1, margin: 15 }}>
<TextInput
placeholder='Write a caption...'
placeholderTextColor='gray'
multiline={true}
style={{ color: 'white', fontSize: 17 }}
onChangeText={handleChange('caption')}
onBlur={handleBlur('caption')}
value={values.caption}
/>
</View>
</View>
<Divider width={0.5} orientation='vertical'/>
<View style={{ alignItems: 'center', marginTop: 15 }}>
<Text style={{ fontSize: 18, fontWeight: 'bold', color: 'white' }}>Choose Image</Text>
</View>
<View style={{ justifyContent: 'space-between', flexDirection: 'column', margin: 20 }}>
<View style={{ justifyContent: 'space-between', flexDirection: 'row', margin: 30 }}>
<Button title='Camera' onPress={handleCameraPress}/>
<Button title='Gallery' onPress={() => navigation.navigate('GalleryView')} />
</View>
<Button onPress={handleSubmit} title='Post' disabled={isvalid} />
</View>
</>
)}
</Formik>
)
}
export default FormikPostUploader
And my CameraView screen :-
import { View, Text, Image, StyleSheet, Button } from 'react-native'
import React, {useState, useEffect} from 'react'
import { Camera } from 'expo-camera'
import { TouchableOpacity } from 'react-native'
import { useNavigation } from '#react-navigation/native'
import { PLACEHOLDER_IMG } from '../components/newPost/FormikPostUploader'
export const takePicture = async(camera) => {
const data = await camera.takePictureAsync(null)
return data.uri
}
const Header = () =>{
const navigation = useNavigation()
return (
<View style = {styles.headerContainer}>
<TouchableOpacity style = {{marginBottom:15}} onPress={() => navigation.goBack()}>
<Image source = {require('../assets/back.png')} style = {{width:35, height:35, margin:20}}/>
</TouchableOpacity>
<Text style={{color:'white', fontWeight: '700', fontSize:20, marginRight: 25, marginTop:35, marginBottom:15}}>New Post</Text>
<Text> </Text>
</View>
)
}
const CameraView = () => {
const UserImage = takePicture()
const navigation = useNavigation()
const [hasCameraPermission, setHasCameraPermission] = useState(null)
const [thumbnailUrl, setThumbnailUrl] = useState(PLACEHOLDER_IMG)
const [camera, setCamera] = useState(null)
const [type, setType] = useState(Camera.Constants.Type.back)
const captureImage = async () => {
if (camera) {
const UserImage = await takePicture(camera)
setThumbnailUrl(UserImage)
}
}
useEffect(() => {
(async() => {
const cameraStatus = await Camera.requestCameraPermissionsAsync()
setHasCameraPermission(cameraStatus.status === 'granted')})()},
[])
if (hasCameraPermission === null) {
return <View/>
}
if (hasCameraPermission === false){
return <Text>Enable access for Camera to proceed</Text>
}
return (
<View style={{ flex: 1, backgroundColor: 'black'}}>
<Header/>
<Camera
ref = {ref => setCamera(ref)}
style={styles.fixedRatio}
type={type}
ratio={'1:1'}/>
<View style = {styles.cameraContainer}>
<TouchableOpacity onPress={() => {setType(type === Camera.Constants.Type.back ? Camera.Constants.Type.front : Camera.Constants.Type.back)}}>
<Image source={require('../assets/turn-camera.png')} style = {{width:70, height:70, margin: 15}}/>
</TouchableOpacity>
<TouchableOpacity onPress={() => {captureImage(), navigation.goBack(), console.log(UserImage)}}>
<Image source={require('../assets/camera-shutter.png')} style = {{width:70, height:70, marginRight:60}}/>
</TouchableOpacity>
</View>
</View>
)
}
const styles = StyleSheet.create({
cameraContainer: {
flex:0.15,
backgroundColor: 'black',
flexDirection:'row',
justifyContent: 'space-between',
alignItems: 'center',
},
fixedRatio: {
flex:0.99,
aspectRatio:0.9
},
headerContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
backgroundColor:'black'
},
icon: {
width:25,
height: 25,
marginHorizontal:15,
marginTop:30,
},
iconContainer: {
flexDirection:'row',
justifyContent: 'space-between',
height:50,
},
}
)
export default CameraView
Am I doing anything wrong. Can you help me fix this. Thanks in advance!

React Navigation (Native) navigation.navigate isn't working and throwing an undefined error

My Custom Button that should take me home doesn't and give me an "undefined error." I'm pretty sure its because the Stack Navigator stuff is in the main file, but I don't know how to give this code file access to it and my Google efforts and the Docs have been unsuccessful. Any help on this simple issue would be appreciated.
import React from 'react';
import { View, Text, Image, StyleSheet } from 'react-native';
import CustomButton from './CustomButton';
import { useFonts } from 'expo-font';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import player from './Player';
import App from './App';
import usePotion from './UsePotion';
import { useState } from 'react';
import { useEffect } from 'react';
function BattleScreen({ navigation }) {
const [fontsLoaded, error] = useFonts({
'Valorax': require('./Fonts/Valorax.otf'),
});
if (!fontsLoaded) {
return <Text>Loading...</Text>;
}
return (
<View style={styles.container}>
<Text style={styles.text}>{player.potions}</Text>
<View style={styles.topHalf}>
</View>
<View style={styles.bottomHalf}>
<View style={styles.buttonRow}>
<CustomButton onPress={() => handleAttack()} title='Attack'></CustomButton>
<CustomButton onPress={() => handleMagic()} title='Magic'></CustomButton>
</View>
<View style={styles.buttonRow}>
<CustomButton onPress={usePotion()} title='Use Potion'></CustomButton>
<CustomButton onPress={() => handleRun()} title='Run'></CustomButton>
<CustomButton onPress={() => navigation.navigate('Home')} title="Home"></CustomButton>
</View>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#000000',
},
topHalf: {
flex: 1,
color: 'white',
},
bottomHalf: {
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap'
},
buttonRow: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-evenly',
flexWrap: 'wrap'
},
text: {
fontSize: 90,
color: 'white',
fontFamily: "Valorax",
}
});
export default BattleScreen;
**strong text**
Try using the useNavigation hook (https://reactnavigation.org/docs/use-navigation/):
import { useNavigation } from '#react-navigation/native';
function BattleScreen() {
const [fontsLoaded, error] = useFonts({
'Valorax': require('./Fonts/Valorax.otf'),
});
const navigation = useNavigation()
if (!fontsLoaded) {
return <Text>Loading...</Text>;
}
return (
<View style={styles.container}>
<Text style={styles.text}>{player.potions}</Text>
<View style={styles.topHalf}>
</View>
<View style={styles.bottomHalf}>
<View style={styles.buttonRow}>
<CustomButton onPress={() => handleAttack()} title='Attack'></CustomButton>
<CustomButton onPress={() => handleMagic()} title='Magic'></CustomButton>
</View>
<View style={styles.buttonRow}>
<CustomButton onPress={usePotion()} title='Use Potion'></CustomButton>
<CustomButton onPress={() => handleRun()} title='Run'></CustomButton>
<CustomButton onPress={() => navigation.navigate('Home')} title="Home"></CustomButton>
</View>
</View>
</View>
);
}

Components display perfectly on web view but aren't being displayed on android view in React Native

I'm building an instagram clone using React Native with Homescreen consisting of custom Header and Imagepost components,but it isn't showing up properly on android although it displays perfectly on web view(images below).
I only added the Text and the Test Button for testing purposes
HomeScreen.js:
import React, { useEffect, useState } from "react";
import { View, Text, TouchableOpacity, Button } from "react-native";
import axios from "axios";
import ImagePost from "../../components/ImagePost";
import Header from "../../components/Header";
import Ionicons from "react-native-vector-icons/Ionicons";
import useStore from "../../store";
const HomeScreen = ({ navigation }) => {
const [posts, setposts] = useState([]);
const [current, setcurrent] = useState(null);
const user = useStore((state) => state.currentUser);
const setcurrentUser = useStore((state) => state.setcurrentUser);
useEffect(() => {
axios.get("http://localhost:5000/posts").then((response) => {
console.log(response.data.posts);
setposts(response.data.posts);
});
}, []);
return (
<View>
<Header navigation={navigation} />
<Text>huidhoasodhiohdp</Text>
<Button title="test" />
{console.log("now user", user)}
{console.log("posts", posts)}
{posts &&
posts.map((post) => {
return (
<View key={post._id}>
<ImagePost post={post} navigation={navigation} />
{console.log("This post is", post)}
</View>
);
})}
</View>
);
};
export default HomeScreen;
Header.js:
import React from "react";
import { View, TouchableOpacity, Text } from "react-native";
import Ionicons from "react-native-vector-icons/Ionicons";
import useStore from "../store";
const Header = ({ navigation }) => {
console.log("header navigation", navigation);
const user = useStore((state) => state.currentUser);
return (
<View
style={{
flex: 1,
flexDirection: "row",
justifyContent: "space-between",
backgroundColor: "white",
}}
>
<TouchableOpacity
onPress={() => navigation.navigate("AddScreen")}
style={{ margin: "5%" }}
>
<Ionicons name="add-outline" size={25} color="black" />
</TouchableOpacity>
{user && <Text>{user.username}</Text>}
{user && console.log(user.username)}
<TouchableOpacity style={{ margin: "5%" }}>
<Ionicons name="chatbubble-ellipses-outline" size={25} color="black" />
</TouchableOpacity>
</View>
);
};
export default Header;
ImagePost.js :
import React from "react";
import { View, Text, Image, TouchableOpacity, Button } from "react-native";
import Ionicons from "react-native-vector-icons/Ionicons";
const ImagePost = ({ post, navigation }) => {
return (
<View>
<View style={{ flex: 1, flexDirection: "row", alignItems: "center" }}>
<Image
style={{
width: 50,
height: 50,
borderRadius: 50,
marginRight: "3%",
}}
source={post.creator.pic}
/>
<Text style={{ fontWeight: "bold" }}>User</Text>
</View>
<View style={{ width: "100%", height: 450 }}>
<Image
style={{ resizeMode: "cover", height: "100%" }}
source={post.file}
/>
<View style={{ flex: 1, flexDirection: "row", marginBottom: "6%" }}>
<TouchableOpacity style={{ marginRight: "1%" }}>
<Ionicons name="heart-outline" size={25} color="black" />
</TouchableOpacity>
<TouchableOpacity
style={{ marginRight: "1%" }}
onPress={() =>
navigation.navigate("CommentsScreen", { postId: post._id })
}
>
<Ionicons name="chatbubble-outline" size={25} color="black" />
</TouchableOpacity>
</View>
<Text>
<Text style={{ fontWeight: "bold", marginRight: "5%" }}>
{post.creator.userName}
</Text>
{post.description}
</Text>
</View>
</View>
);
};
export default ImagePost;
Android view
Web view

How to add information pop-up for TextInput in React Native?

I want to achieve something like this in React Native:
I have a TextInput component and I want to put an icon to the right side. The user can click it, then I can display some text in a modal or in a another component.
Is this possible in react native?
return(
<View style={styles.container}>
<TextInput
placeholder="Állat neve"
value={AllatNev}
style={styles.textBox}
onChangeText={(text) => setAllatNev(text)}
/>
</View>
);
}
)
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: color_theme_light.bodyBackground
justifyContent: 'center',
alignItems:'center'
},
textBox:{
borderWidth:2,
borderColor: color_theme_light.textBoxBorder,
margin:15,
borderRadius:10,
padding: 10,
fontFamily:'Quicksand-Medium'
},
});
Yes -- you can position your info button over the TextInput using absolute positioning and a zIndex, for example:
import * as React from 'react';
import { Text, View, StyleSheet, TextInput, TouchableOpacity } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<View style={styles.textBoxParent}>
<TextInput style={styles.textBox} placeholder="Állat neve"/>
<TouchableOpacity style={styles.textBoxButton} onPress={() => {
//launch your modal
}}>
<Text>i</Text>
</TouchableOpacity>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
textBoxParent: {
justifyContent: 'center'
},
textBox:{
borderWidth:2,
borderColor: 'gray',
margin:15,
borderRadius:10,
padding: 10,
},
textBoxButton: {
position: 'absolute',
right: 20,
zIndex: 100,
width: 20,
height: 20,
borderWidth: 1,
borderRadius: 10,
justifyContent: 'center',
alignItems: 'center'
}
});
Working example: https://snack.expo.dev/OFMTc8GHE
Heres a full example of what you want (https://snack.expo.dev/bjzBFuE4W). And below I explain the code.
Fist I made a Modal from react native that takes in modalVisible, setModalVisible, and appears when modalVisible is true.
import * as React from 'react';
import { Text, View, StyleSheet,TextInput ,TouchableOpacity,Modal} from 'react-native';
import { AntDesign } from '#expo/vector-icons';
import { MaterialIcons } from '#expo/vector-icons';
const ModalInfo = ({modalVisible, setModalVisible})=>{
return (
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
setModalVisible(!modalVisible);
}}
>
<View style={{
flex: 1,
justifyContent: "center",
alignItems: "center",
}}>
<View
style={{
width:200,height:200,backgroundColor:"gray",borderWidth:2,
justifyContent:"center",alignItems:"center"
}}
>
<TouchableOpacity onPress={()=>{setModalVisible(false)}}>
<MaterialIcons name="cancel" size={24} color="black" />
</TouchableOpacity>
</View>
</View>
</Modal>
)
}
Next I made a View to wrap around the textInput so I can also add an svg of the info icon. And then set the outside view to have flexDirection:"row", so everything would be ordered the way you wan't.
const TextInputWithModal = ()=>{
const [modalVisible, setModalVisible] = React.useState(false);
const [AllatNev,setAllatNev]= React.useState("");
return (
<View style={styles.textInputContainer}>
<TextInput
placeholder="Állat neve"
value={AllatNev}
style={styles.textBox}
onChangeText={(text) => setAllatNev(text)}
/>
<TouchableOpacity onPress={()=>{setModalVisible(true)}}>
<AntDesign name="infocirlceo" size={24} color="black" />
</TouchableOpacity>
<ModalInfo modalVisible={modalVisible} setModalVisible={setModalVisible}/>
</View>
)
}
export default function App() {
return (
<View style={styles.container}>
<TextInputWithModal/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems:"center",
},
textInputContainer:{
borderRadius:10,
padding: 10,
flexDirection:"row",
margin:15,
borderWidth:2,
},
textBox:{
fontFamily:'Quicksand-Medium',
marginRight:20,
},
});

How to i read field data from firestore in react native?

I want to display the temp value in application from fire store but I don't know how to do it by using hook (온도 means temperature)
please help me this is my code. v v
import React ,{useState,useEffect} from 'react';
import Iconicons from 'react-native-vector-icons/Ionicons';
import firestore, { firebase } from '#react-native-firebase/firestore';
import {
SafeAreaView,
ScrollView,
StyleSheet,
TouchableOpacity,
Text,
View}
from 'react-native';
const temp = ({navigation}) => {
return (
<SafeAreaView style={styles.top}>
<View style={styles.array}>
<TouchableOpacity onPress={() => {navigation.pop()}}>
<Iconicons name={'arrow-back-outline'} size={40} color={'white'}/>
</TouchableOpacity>
<Text style={styles.word}>온도</Text>
<Text> </Text>
</View>
<ScrollView style={styles.container}>
<View style={styles.body}>
<View style={styles.box}>
<Text style={styles.text}>온도:{temp} </Text>
</View>
</View>
</ScrollView>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
backgroundColor: 'skyblue',
flex: 1,
},
top:{
backgroundColor: '#007ccc',
flex: 1,
},
body:{
marginTop:100,
alignItems:'center',
justifyContent:'center',
},
word:{
fontSize:20,
color:'white',
},
array:{
justifyContent:'space-between',
flexDirection:'row',
},
box:{
justifyContent:'center',
backgroundColor:'white',
borderRadius:30,
width:300,
height:300,
},
text:{
fontSize:50,
},
});
export default temp;
This is my data from firestore:

Categories

Resources