i need to show details of the post which user was searching for, but there are two…
- User
i need to show details of the post which user was searching for, but there are two collections FutureMK and PastMK. Here is my code where i need to use redirect to show more data import { Text, View, Image, Pressable } from ‘react-native’; import { gStyle } from ‘…/styles/style’; import React from ‘react’;
export default function Result({ item }) {
return ( <View style={[gStyle.bookedMK, {flex:1}]}> <View style={{ flexDirection: ‘column’ }}> {item.name} {item.description.length > 100 ? item.description.substring(0, 100)+‘…’ : item.description } <Pressable style={gStyle.readmore}
Читать далее
); }
- Assistant
To show more details of the post, you need to use React Navigation to navigate to a new screen where you can display all the details of the post. Here is an example code:
- Import the necessary components from React Navigation
import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack';
- Create a new screen component to display the post details
function PostDetailsScreen({ route, navigation }) { const { postId } = route.params; // get the postId parameter passed from the Result screen // use the postId to fetch the post details from the appropriate collection (FutureMK or PastMK) // display the post details in this screen return ( Post Details Screen Post Id: {postId} ); }
- Update the Result component to navigate to the PostDetailsScreen when the user presses the "Читать далее" button
import { useNavigation } from '@react-navigation/native';
export default function Result({ item }) { const navigation = useNavigation();
const onPressReadMore = () => { // navigate to the PostDetailsScreen and pass the postId parameter navigation.navigate('PostDetails', { postId: item.id, collection: item.collection }); };
return ( {item.name} {/* display other post information here */} Читать далее ); }
- Add the PostDetailsScreen to the createStackNavigator function in your App.js file
const Stack = createStackNavigator();
export default function App() { return ( <Stack.Navigator> {/* add other screens here */} <Stack.Screen name="PostDetails" component={PostDetailsScreen} /> </Stack.Navigator> ); }
Note: In the PostDetailsScreen component, you'll need to fetch the post details based on the collection value passed from the Result screen. You can use conditional logic to determine which collection to fetch data from.
- User
ive already have screens import { Text, View, Image, ScrollView, Pressable} from 'react-native'; import { gStyle } from '../styles/style'; import Header from '../components/Header'; import Footer from '../components/Footer'; import { useNavigation } from '@react-navigation/native'; import moment from 'moment';
export default function PastMKInfo({route}) { const navigation = useNavigation(); const {mkData}=route.params; const handleGoBack=()=>{ navigation.goBack(); };
return ( {mkData.name} {new Intl.DateTimeFormat('ru-RU',{ day:'numeric', month:'long', year:'numeric' }).format(mkData.time.toDate())} {mkData.description} Назад ); }
import { Text, View, Image, Pressable, ScrollView } from 'react-native'; import { gStyle } from '../styles/style'; import React, {useState, useEffect} from 'react'; import Header from '../components/Header'; import Footer from '../components/Footer'; import { Ionicons, MaterialCommunityIcons } from '@expo/vector-icons'; import { useNavigation } from '@react-navigation/native'; import moment from 'moment'; import {firebase} from '../Firebase/firebase'; import 'firebase/compat/auth'; import 'firebase/compat/database'; import 'firebase/compat/firestore';
export default function SignUpForMK({route}) { const [userAuthenticated, setUserAuthenticated] = useState(false); useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { if (user) { setUserAuthenticated(true); } else { setUserAuthenticated(false); } });
return unsubscribe; }, []); const {mkData}=route.params; const navigation = useNavigation(); const bookMK=()=>{ const currentUserID=firebase.auth().currentUser.uid; const bookedMKData={ name:mkData.name, time:mkData.time.toDate().toISOString(), image:mkData.image, price:mkData.price }; firebase .database() .ref(`users/${currentUserID}/bookedMK`) .push(bookedMKData) .then(()=>{ navigation.navigate('Profile'); }) }return ( {mkData.name} {new Intl.DateTimeFormat('ru-RU',{ day:'numeric', month:'long', year:'numeric', hour:'numeric', minute:'numeric', hour12:false }).format(mkData.time.toDate())} Цена: {mkData.price} Р. {mkData.description} {mkData.person} человек {mkData.timeOfMK} час(а) {userAuthenticated ? Забронировать : <Pressable style={gStyle.SupMoreDetails} onPress={()=>navigation.navigate('Auth')} > Забронировать }
</View> </View> </View> <Footer/> </ScrollView> </View>); }
- Assistant
Great! In that case, you can add a button to the PastMKInfo screen that will navigate to the SignUpForMK screen where the user can sign up for the relevant MK. Here's an example code:
- Add a button to the PastMKInfo screen that will navigate to the SignUpForMK screen
import { useNavigation } from '@react-navigation/native';
export default function PastMKInfo({route}) { const navigation = useNavigation(); const {mkData}=route.params; const handleGoBack=()=>{ navigation.goBack(); };
const handleSignUp=()=>{ navigation.navigate('SignUpForMK', { mkData }); };
return ( {/* display other information /} Записаться на мастер-класс {/ display other information */} ); }
- Create a new screen component SignUpForMK to display details of the MK and allow the user to sign up
import { useNavigation } from '@react-navigation/native';
export default function SignUpForMK({route}) { const [userAuthenticated, setUserAuthenticated] = useState(false); const {mkData}=route.params; const navigation = useNavigation();
useEffect(() => { const unsubscribe = firebase.auth().onAuthStateChanged(user => { if (user) { setUserAuthenticated(true); } else { setUserAuthenticated(false); } });
return unsubscribe;}, []);
const handleSignUp=()=>{ const currentUserID=firebase.auth().currentUser.uid; const bookedMKData={ name:mkData.name, time:mkData.time.toDate().toISOString(), image:mkData.image, price:mkData.price }; firebase .database() .ref(
users/${currentUserID}/bookedMK) .push(bookedMKData) .then(()=>{ navigation.navigate('Profile'); }) };return ( {/* display other information /} {userAuthenticated ? Записаться на мастер-класс : <Pressable onPress={()=>navigation.navigate('Auth')}> Записаться на мастер-класс } {/ display other information */} ); }
Note: In the SignUpForMK screen, you'll need to fetch the MK details based on the mkData parameter passed from the PastMKInfo screen. You can use this information to display the relevant details on the screen and allow the user to sign up. Also, make sure to import the necessary Firebase components for the Firebase functionality to work.
- User
мне не надо с прошедших мк записываться на новые, мне нужно, чтобы юзер, когда нашел то, что искал, смог перейти на экран с информацией либо из коллекции PastMK, либо FutureMK. Как мне это сделать
- Assistant
Для этого вам нужно изменить ваш список (список FutureMK и PastMK) таким образом, чтобы он содержал не только пользовательские данные, но и информацию о том, из какой коллекции эти данные были получены. Например, вы можете добавить новый ключ "collection", который будет содержать значение "FutureMK" или "PastMK".
Затем в вашем компоненте Result необходимо добавить обработчик для нажатия на список. Когда пользователь нажимает на список, вы можете передать объект материал-контента (MK) со всеми данными в следующий экран.
Для этого вы можете использовать Navigation.navigate() и передать параметр в следующий экран. Затем на экране деталей, вы можете определить, из какой коллекции были получены данные, и на основе этого вы можете определить, какие данные отображать. Вот пример кода:
- Обновите список отображаемых данных FutureMK и PastMK
// Inside your FutureMK screen component
const [futureMks, setFutureMks] = useState([]); useEffect(() => { const futureMKRef = firebase.firestore().collection('FutureMK');
futureMKRef.onSnapshot((querySnapshot) => { const list = []; querySnapshot.forEach((doc) => { const {title, date, description, image} = doc.data(); list.push({ id: doc.id, title, date, description, image, collection: 'FutureMK' // add collection value to identify where this data is coming from }); });
setFutureMks(list);});
return () => futureMKRef(); }, []);
// Inside your PastMK screen component
const [pastMks, setPastMks] = useState([]); useEffect(() => { const pastMKRef = firebase.firestore().collection('PastMK');
pastMKRef.onSnapshot((querySnapshot) => { const list = []; querySnapshot.forEach((doc) => { const {title, date, description, image} = doc.data(); list.push({ id: doc.id, title, date, description, image, collection: 'PastMK' // add collection value to identify where this data is coming from }); });
setPastMks(list);});
return () => pastMKRef(); }, []);
// Use FlatList to display the FutureMK and PastMK list
<FlatList data={futureMks.concat(pastMks)} renderItem={({item}) => } keyExtractor={(item) => item.id} />
- Обновите компонент Result, чтобы навигировать на экран деталей, передав параметр
import { useNavigation } from '@react-navigation/native';
export default function Result({ item }) { const navigation = useNavigation();
const onPressReadMore = () => { // navigate to the MKDetails screen and pass the full MK object navigation.navigate('MKDetails', { mkData: item }); };
return ( {item.title} {/* display other MK information here */} Смотреть детали ); }
- Создайте новый экран компонента MKDetails, который будет отображать подробную информацию о материал-контенте, в зависимости от его коллекции из которой он был получен.
import { Text, View, Image } from 'react-native';
export default function MKDetails({route}) { const {mkData} = route.params;
return ( {mkData.title} {/* display other MK details based on its collection value */} {mkData.collection === 'FutureMK' && FutureMK Details } {mkData.collection === 'PastMK' && PastMK Details } ); }
Note: В компоненте MKDetails, вы должны отобразить различные детали, в зависимости от того, из какой коллекции пришли данные. В моем примере я использую условный оператор if, но вы можете использовать любую другую логику для отображения данных.
- User
i have already have details for PastMK and FutureMK, i just need to redirect user from result to the FutureMK or the PastMK how can i do it??
- Assistant
In this case, you can create two separate screens for FutureMK and PastMK details, and then navigate the user to the appropriate screen when they click on a Result item.
Here is an example of how to do it:
-
Create two separate screens for FutureMK and PastMK details You can create two separate screens named "FutureMKDetails" and "PastMKDetails" respectively. These screens will display the relevant details of the selected MK.
-
Update the Result component to navigate to the appropriate screen Inside the onPressReadMore function of the Result component, you can use the navigation prop to navigate the user to the appropriate screen based on the collection value of the selected MK. Here's a code snippet to demonstrate:
import { useNavigation } from '@react-navigation/native'; export default function Result({ item }) { const navigation = useNavigation(); const onPressReadMore = () => { if (item.collection === 'FutureMK') { navigation.navigate('FutureMKDetails', { mkData: item }); } else if (item.collection === 'PastMK') { navigation.navigate('PastMKDetails', { mkData: item }); } }; return ( <View> <Text>{item.title}</Text> {/* display other MK information here */} <Pressable onPress={onPressReadMore}> <Text>Смотреть детали</Text> </Pressable> </View> ); }- Pass the MK data to the relevant screen When you navigate to the FutureMKDetails or PastMKDetails screen, you can pass the entire MK object as a parameter, just like you did in the Result component. Here's a code snippet to demonstrate:
export default function FutureMKDetails({ route }) { const { mkData } = route.params; return ( <View> <Text>{mkData.title}</Text> {/* display other FutureMK details here */} </View> ); } export default function -