Ibrahim Anam
Ibrahim Anam

Reputation: 51

Navigation problems

Whenever I am in History.js and I click on one of the products lists to navigate into another page which should opens a new page for more description and be able to contact the seller... so the problem that I am facing is. whenever I click any item in History.js nothing happens in the that page. but when I open Home.js then I see that it got navigated here in Home.js rather than History.js.. what am I missing here?

Home.js

import React from "react";
import {
  View,
  Text,
  Button,
  SafeAreaView,
  TextInput,
  StatusBar,
  Platform,
  ScrollView,
  Image,
  StyleSheet,
  TouchableOpacity,
} from "react-native";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import ProductsList from "../../components/productsList/ProductsList";
import Icon from "react-native-vector-icons/Ionicons";
import { fontSize } from "styled-system";
import Location from "../components/Location";

export default function Search({ navigation }) {
  return (
    <SafeAreaView style={{ flex: 1 }}>
      <View style={{ flex: 1 }}>
        <View
          style={{
            height: 80,
            backgroundColor: "white",
            borderBottomWidth: 1,
            borderBottomColor: "#dddddd",
          }}
        >
          <View
            style={{
              flexDirection: "row",
              padding: 10,
              backgroundColor: "white",
              marginHorizontal: 20,
              shadowOffset: { width: 0, height: 0 },
              shadowColor: "black",
              shadowOpacity: 0.2,
              borderRadius: 50,
              elevation: 1,
            }}
          >
            <Icon name="ios-search" size={20} style={{ marginRight: 10 }} />
            <TextInput
              underlineColorAndroid="transparent"
              placeholder="City, airport, adrerss, or hotel"
              placeholderTextColor="grey"
              style={{ flex: 1, fontWeight: "700", backgroundColor: "white" }}
            />
          </View>
        </View>

        <ScrollView
          horizontal={true}
          showsHorizontalScrollIndicator={false}
          scrollEventThrottle={16}
        >
          <View style={{ height: 175 }}>
            <Image
              source={require("../home/homepage.jpeg")}
              resizeMode="contain"
            />
          </View>
        </ScrollView>

        <ScrollView scrollEventThrottle={16}>
          <View
            style={{
              flex: 1,
              backgroundColor: "white",
              paddingTop: 30,
              paddingRight: 40,
              justifyContent: "center",
              alignItems: "center",
            }}
          >
            <Text
              style={{
                alignItems: "center",
                fontSize: 24,
                fontWeight: "700",
                paddingHorizontal: 25,
                marginLeft: 50,
                borderColor: "grey",
                height: 50,
                width: 230,
                shadowOpacity: 0.5,
                borderWidth: 0.5,
                paddingTop: 10,
                backgroundColor: "#f5bd1f",
                justifyContent: "center",
              }}
            >
              FIND YOUR RIDE
            </Text>

            <View style={{ height: 130, marginTop: 20 }}>
              <ScrollView
                horizontal={true}
                showsHorizontalScrollIndicator={false}
              >
                <TouchableOpacity>
                  <Location
                    imageUri={require("../home/nicosia.jpg")}
                    name="Nicosia"
                  />
                </TouchableOpacity>

                <TouchableOpacity>
                  <Location
                    imageUri={require("../home/kyrenia.jpg")}
                    name="Kyrenia"
                  />
                </TouchableOpacity>

                <TouchableOpacity>
                  <Location
                    imageUri={require("../home/famagusta.jpg")}
                    name="Famagusta"
                  />
                </TouchableOpacity>

                <TouchableOpacity>
                  <Location
                    imageUri={require("../home/lefke.png")}
                    name="Lefke"
                  />
                </TouchableOpacity>
              </ScrollView>
            </View>

            <Text
              style={{
                flex: 1,
                fontWeight: "bold",
                fontSize: 24,
                alignItems: "center",
                color: "#f5bd1f",
                paddingLeft: 20,
              }}
            >
              / / / / /
            </Text>
            <View style={{ marginTop: 40, paddingHorizontal: 20 }}>
              <View>
                <Text
                  style={{
                    fontSize: 24,
                    fontWeight: "700",
                    paddingLeft: 40,
                  }}
                >
                  <View>
                    <MaterialCommunityIcons
                      name="face-agent"
                      size={30}
                      style={{ paddingLeft: 10, color: "#f5bd1f" }}
                    />
                  </View>
                  24/7 customer support
                </Text>
                <Text
                  style={{ paddingLeft: 80, marginTop: 20, marginBottom: 25 }}
                >
                  {
                    "Rest easy knowing that everyone in \nthe Rent in cars community is screened, \nand 24/7 customer support and \nroadside assistant are just a tap away."
                  }
                </Text>
              </View>

              <View>
                <Text
                  style={{
                    fontSize: 24,
                    fontWeight: "700",
                    paddingLeft: 40,
                  }}
                >
                  <View>
                    <MaterialCommunityIcons
                      name="car"
                      size={30}
                      style={{
                        paddingLeft: 10,
                        color: "#f5bd1f",
                        marginTop: 20,
                      }}
                    />
                  </View>
                  Endless options
                </Text>
                <Text
                  style={{ paddingLeft: 80, marginTop: 20, marginBottom: 25 }}
                >
                  {
                    "Choose from hundreds of models\nyou won't find anywhere else. Pick it \nup or get it delivered where you \nwant it."
                  }
                </Text>
              </View>

              <View>
                <Text
                  style={{
                    fontSize: 24,
                    fontWeight: "700",
                    paddingLeft: 40,
                  }}
                >
                  <View>
                    <MaterialCommunityIcons
                      name="security"
                      size={30}
                      style={{ paddingLeft: 10, color: "#f5bd1f" }}
                    />
                  </View>
                  Drive confidently
                </Text>
                <Text
                  style={{ paddingLeft: 80, marginTop: 20, paddingBottom: 40 }}
                >
                  {
                    "Drive confidently with your choice \nof protection plans - all plans \ninclude varying levels of third party \nliability insrurance from Liberty \nMutual and physical damage \nprotection from Rent in Car that caps\nyour out of pocket responsibility for \ndamage to your host's car during \nyour trip."
                  }
                </Text>
              </View>
              <Text
                style={{
                  fontWeight: "bold",
                  fontSize: 24,
                  alignItems: "center",
                  color: "#f5bd1f",
                  paddingLeft: 150,
                }}
              >
                / / / / /
              </Text>
              <View style={{ marginTop: 30 }}></View>
            </View>
          </View>
        </ScrollView>
      </View>
    </SafeAreaView>
  );
  const styles = StyleSheet.create({
    container: {
      flex: 1,
      alignItems: "center",
      justifyContent: "center",
    },
    red: {
      color: "red",
    },
  });
}

History.js

import moment from "moment";
import React, { useState } from "react";
import Firebase from "../../config/firebase";
import ProductsList from "../../components/productsList/ProductsList";
import {
  FlatList,
  Text,
  View,
  Image,
  TouchableWithoutFeedback,
  TextInput,
  ActivityIndicator,
} from "react-native";
import { Colors } from "../../staticValues/Colors";
import { Devicewidth, productCardWidth } from "../../staticValues/Dimensions";
import { useEffect } from "react";
import { styles } from "../../styles/authStyle";

import { FontAwesome5 } from "@expo/vector-icons";
import { I18n } from "../../helper/Multilanguage";

export default function HistoryList({ navigation }) {
  const [filtredList, setfiltredList] = useState([]);

  const [isFetching, setisFetching] = useState(false);
  const [allProduct, setallProduct] = useState([]);
  const [searchInput, setsearchInput] = useState("");

  const [visible, setVisible] = React.useState(true);

  function onRefresh() {
    getAllProdcuts();
  }

  function getAllProdcuts() {
    setisFetching(true);
    Firebase.firestore()
      .collection("Products")
      .get()
      .then((docRef) => {
        var list = [];
        docRef.forEach((elm) => {
          list.push(elm.data());
        });
        setfiltredList(list);
        setallProduct(list);
        setisFetching(false);
      })
      .catch((error) => {
        console.log({ error });
        setisFetching(false);
      });
  }

  useEffect(() => {
    getAllProdcuts();
    const willFocusSubscription = navigation.addListener("focus", () => {
      getAllProdcuts();
    });

    return willFocusSubscription;
  }, []);

  return (
    <View
      style={{
        flex: 1,
      }}
    >
      <View
        style={{
          width: "80%",
          backgroundColor: Colors.lightGray,
          borderRadius: 30,
          height: 45,
          marginBottom: 5,
          justifyContent: "center",
          padding: 20,
          alignSelf: "center",
          marginTop: 10,
        }}
      >
        <FontAwesome5
          name={"search"}
          size={26}
          color={"black"}
          style={styles.inputIcon}
        />
        <TextInput
          style={styles.loginpass}
          placeholder={I18n.t("searchProduct")}
          placeholderTextColor="#fff"
          onChangeText={(input) => {
            setsearchInput(input);
            // filter list
            const SearchResult = allProduct.filter((product) =>
              product.title.toLowerCase().includes(input.toLocaleLowerCase())
            );
            setfiltredList(SearchResult);
          }}
        />
      </View>

      <View
        style={{
          alignItems: "center",
          flex: 1,
        }}
      >
        <FlatList
          ListEmptyComponent={() => {
            return (
              <View>
                {!isFetching && (
                  <Text
                    style={{
                      textAlign: "center",
                      color: Colors.accentColor,
                      fontWeight: "bold",
                      paddingVertical: 20,
                    }}
                  >
                    {I18n.t("noProduct")}
                  </Text>
                )}
              </View>
            );
          }}
          onRefresh={() => onRefresh()}
          refreshing={isFetching}
          keyExtractor={(item) => item.image}
          numColumns={2}
          data={filtredList}
          renderItem={({ item }) => {
            return (
              <TouchableWithoutFeedback
                onPress={() => {
                  navigation.push("ProductDetails", {
                    selectedProduct: item,
                  });
                }}
              >
                <View
                  style={{
                    backgroundColor: "white",
                    alignItems: "center",
                    padding: 3,
                    elevation: 4,
                    borderRadius: 10,
                    margin: 6,
                  }}
                >
                  <View>
                    <Image
                      source={{ uri: item.image }}
                      style={{
                        height: productCardWidth,
                        width: productCardWidth,
                        borderRadius: 10,
                        marginBottom: 5,
                        zIndex: 1,
                      }}
                    />

                    <View
                      style={{
                        alignItems: "center",
                        justifyContent: "center",
                        height: productCardWidth,
                        width: productCardWidth,
                        position: "absolute",
                        backgroundColor: Colors.lightGray,
                        borderRadius: 10,
                        marginBottom: 5,
                        zIndex: 0,
                      }}
                    >
                      <ActivityIndicator
                        color={Colors.accentColor}
                        size={"small"}
                        style={{
                          top: 10,
                          right: 10,
                          position: "absolute",
                        }}
                      />
                      <FontAwesome5
                        name={"image"}
                        size={26}
                        color={"black"}
                        style={
                          {
                            // position: "absolute",
                          }
                        }
                      />
                    </View>
                  </View>
                  <Text
                    style={{
                      color: Colors.dark,
                      fontWeight: "bold",
                      fontSize: 16,
                    }}
                  >
                    {item.title.length > 12
                      ? item.title.slice(0, 12) + "..."
                      : item.title}
                  </Text>
                  <Text
                    style={{
                      fontWeight: "bold",
                    }}
                  >
                    {item.price} {item.currency}
                  </Text>
                </View>
              </TouchableWithoutFeedback>
            );
          }}
        />
      </View>
    </View>
  );
}

This is the HomeStack

import React from "react";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import Home from "../screens/home/Home";
import Profile from "../screens/profile/Profile";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import Messages from "../screens/messages/Messages";
import ProductStack from "./ProductStack";
import { Colors } from "../staticValues/Colors";
import SellProductForm from "../components/sellProduct/SellProductForm";
import History from "../components/history/History";
import ChatStack from "./ChatStack";
import AllMessages from "../screens/messages/AllMessages";
import { I18n } from "../helper/Multilanguage";

export default function HomeStack() {
  const Stack = createNativeStackNavigator();
  const Tab = createBottomTabNavigator();

  return (
    <Tab.Navigator
      initialRouteName="Search"
      screenOptions={{
        tabBarActiveTintColor: Colors.mainColor,
        tabBarActiveTintColor: Colors.mainColor,
        tabBarHideOnKeyboard: true,
      }}
    >
      <Tab.Screen
        name="ProductStack"
        component={ProductStack}
        options={{
          headerShown: false,
          tabBarLabel: I18n.t("Search"),
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons name="magnify" color={color} size={size} />
          ),
        }}
      />

      <Tab.Screen
        name={I18n.t("myProducts")}
        component={History}
        options={{
          tabBarLabel: I18n.t("Trips"),
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons
              name="road-variant"
              color={color}
              size={size}
            />
          ),
        }}
      />

      <Tab.Screen
        name="Messages"
        component={ChatStack}
        options={{
          tabBarLabel: I18n.t("messages"),
          headerShown: false,
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons
              name="message-outline"
              color={color}
              size={size}
            />
          ),
        }}
      />

      <Tab.Screen
        name="SellProductForm"
        component={SellProductForm}
        options={{
          tabBarLabel: I18n.t("Host"),
          title: "Host",
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons name="car" size={size} />
          ),
        }}
      />

      <Tab.Screen
        name={I18n.t("More")}
        component={Profile}
        options={{
          tabBarLabel: I18n.t("More"),
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons
              name="dots-horizontal"
              color={color}
              size={size}
            />
          ),
        }}
      />
    </Tab.Navigator>
  );
}

This is the productStack

import { createNativeStackNavigator } from "@react-navigation/native-stack";
import React from "react";
import { I18n } from "../helper/Multilanguage";
import Home from "../screens/home/Home";
import ProductDetails from "../screens/product/ProductDetails";

export default function ProductStack() {
  const Stack = createNativeStackNavigator();

  return (
    <Stack.Navigator>
      <Stack.Screen
        options={{
          title: I18n.t("home"),
        }}
        name="Home"
        component={Home}
      />
      <Stack.Screen
        options={{
          title: I18n.t("productDetails"),
        }}
        name="ProductDetails"
        component={ProductDetails}
      />
    </Stack.Navigator>
  );
}

this is root.js

import React, { useState, useEffect } from "react";
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import AuthStack from "./AuthStack";
import HomeStack from "./HomeStack";
import Firebase from "../config/firebase";
import { Text } from "react-native";
import { setCurrentUser } from "../staticValues/CurrentUser";
import Splach from "../components/Splach";

export default function Root() {
  const Stack = createNativeStackNavigator();
  // Set an initializing state whilst Firebase connects
  const [initializing, setInitializing] = useState(true);
  const [user, setUser] = useState();

  // Handle user state changes
  function onAuthStateChanged(curentUser) {
    setCurrentUser(curentUser);
    setUser(curentUser);
    if (initializing) setInitializing(false);
  }

  useEffect(() => {
    const subscriber = Firebase.auth().onAuthStateChanged(onAuthStateChanged);
    return subscriber; // unsubscribe on unmount
  }, []);
  if (initializing) {
    return <Splach />;
  } else {
    return (
      <NavigationContainer>
        {user ? (
          <Stack.Navigator
            screenOptions={{
              headerShown: false,
            }}
          >
            <Stack.Screen name="HomeStack" component={HomeStack} />
          </Stack.Navigator>
        ) : (
          <Stack.Navigator
            screenOptions={{
              headerShown: false,
            }}
          >
            <Stack.Screen name="AuthStack" component={AuthStack} />
          </Stack.Navigator>
        )}
      </NavigationContainer>
    );
  }
}

Upvotes: 0

Views: 139

Answers (1)

Gavin D&#39;mello
Gavin D&#39;mello

Reputation: 433

Okay so the issue in your code is that you are currently in a different Tab/Stack ie the history stack but the file you are accessing is in the ProductStack, so when you call the navigator it does what it is supposed to do, ie. navigate to the ProductDetails page, but since it's declared in the ProductStack, the updation happens there itself.

To solve your issue, the following things need to be done.

  1. Create a HistoryStack which will contain 2 screens. First is "History.js" and the second is "ProductDetails.js". NOTE: While declaring/using a class in multiple stacks(in your case - "ProductDetails.js", you need to use/provide a different/unique name to that class inside a stack

Example:

<Stack.Screen name="UNIQUE NAME HERE" component={Original name of your Js file. Eg. "ProductDetails"} />
  1. In place of History in your TabNavigation, pass HistoryStack which you just created(I have created the HistoryStack for you below)

  2. In your History.js file, when you want to navigate to the ProductDetails screen, use the below code:

    navigation.push("ProductDetailsHistoryTab", { selectedProduct: item });

HomeStack

import React from "react";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import Home from "../screens/home/Home";
import Profile from "../screens/profile/Profile";
import { createBottomTabNavigator } from "@react-navigation/bottom-tabs";
import { MaterialCommunityIcons } from "@expo/vector-icons";
import Messages from "../screens/messages/Messages";
import ProductStack from "./ProductStack";
import { Colors } from "../staticValues/Colors";
import SellProductForm from "../components/sellProduct/SellProductForm";
import HistoryStack from "./HistoryStack";
import ChatStack from "./ChatStack";
import AllMessages from "../screens/messages/AllMessages";
import { I18n } from "../helper/Multilanguage";

export default function HomeStack() {
  const Stack = createNativeStackNavigator();
  const Tab = createBottomTabNavigator();

  return (
    <Tab.Navigator
      initialRouteName="Search"
      screenOptions={{
        tabBarActiveTintColor: Colors.mainColor,
        tabBarActiveTintColor: Colors.mainColor,
        tabBarHideOnKeyboard: true,
      }}
    >
      <Tab.Screen
        name="ProductStack"
        component={ProductStack}
        options={{
          headerShown: false,
          tabBarLabel: I18n.t("Search"),
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons name="magnify" color={color} size={size} />
          ),
        }}
      />

      <Tab.Screen
        name={I18n.t("myProducts")}
        //Replaced History class with a HistoryStack
        component={HistoryStack}
        options={{
          tabBarLabel: I18n.t("Trips"),
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons
              name="road-variant"
              color={color}
              size={size}
            />
          ),
        }}
      />

      <Tab.Screen
        name="Messages"
        component={ChatStack}
        options={{
          tabBarLabel: I18n.t("messages"),
          headerShown: false,
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons
              name="message-outline"
              color={color}
              size={size}
            />
          ),
        }}
      />

      <Tab.Screen
        name="SellProductForm"
        component={SellProductForm}
        options={{
          tabBarLabel: I18n.t("Host"),
          title: "Host",
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons name="car" size={size} />
          ),
        }}
      />

      <Tab.Screen
        name={I18n.t("More")}
        component={Profile}
        options={{
          tabBarLabel: I18n.t("More"),
          tabBarIcon: ({ color, size }) => (
            <MaterialCommunityIcons
              name="dots-horizontal"
              color={color}
              size={size}
            />
          ),
        }}
      />
    </Tab.Navigator>
  );
}

HistoryStack

import { createNativeStackNavigator } from "@react-navigation/native-stack";
import React from "react";
import { I18n } from "../helper/Multilanguage";
import History from "../components/history/History";
import ProductDetails from "../screens/product/ProductDetails";

export default function HistoryStack() {
  const Stack = createNativeStackNavigator();

  return (
    <Stack.Navigator>
      <Stack.Screen
        options={{
          title: I18n.t("home"),
        }}
        name="History"
        component={History}
      />
      <Stack.Screen
        options={{
          title: I18n.t("productDetails"),
        }}
        name="ProductDetailsHistoryTab"
        component={ProductDetails}
      />
    </Stack.Navigator>
  );
}

And now for the History.js

function onRefresh() {
    getAllProdcuts();
  }

  function getAllProdcuts() {
    setisFetching(true);
    Firebase.firestore()
      .collection("Products")
      .get()
      .then((docRef) => {
        var list = [];
        docRef.forEach((elm) => {
          list.push(elm.data());
        });
        setfiltredList(list);
        setallProduct(list);
        setisFetching(false);
      })
      .catch((error) => {
        console.log({ error });
        setisFetching(false);
      });
  }

  useEffect(() => {
    getAllProdcuts();
    const willFocusSubscription = navigation.addListener("focus", () => {
      getAllProdcuts();
    });

    return willFocusSubscription;
  }, []);

  return (
    <View
      style={{
        flex: 1,
      }}
    >
      <View
        style={{
          width: "80%",
          backgroundColor: Colors.lightGray,
          borderRadius: 30,
          height: 45,
          marginBottom: 5,
          justifyContent: "center",
          padding: 20,
          alignSelf: "center",
          marginTop: 10,
        }}
      >
        <FontAwesome5
          name={"search"}
          size={26}
          color={"black"}
          style={styles.inputIcon}
        />
        <TextInput
          style={styles.loginpass}
          placeholder={I18n.t("searchProduct")}
          placeholderTextColor="#fff"
          onChangeText={(input) => {
            setsearchInput(input);
            // filter list
            const SearchResult = allProduct.filter((product) =>
              product.title.toLowerCase().includes(input.toLocaleLowerCase())
            );
            setfiltredList(SearchResult);
          }}
        />
      </View>

      <View
        style={{
          alignItems: "center",
          flex: 1,
        }}
      >
        <FlatList
          ListEmptyComponent={() => {
            return (
              <View>
                {!isFetching && (
                  <Text
                    style={{
                      textAlign: "center",
                      color: Colors.accentColor,
                      fontWeight: "bold",
                      paddingVertical: 20,
                    }}
                  >
                    {I18n.t("noProduct")}
                  </Text>
                )}
              </View>
            );
          }}
          onRefresh={() => onRefresh()}
          refreshing={isFetching}
          keyExtractor={(item) => item.image}
          numColumns={2}
          data={filtredList}
          renderItem={({ item }) => {
            return (
              <TouchableWithoutFeedback
                onPress={() => {
                  navigation.push("ProductDetailsHistoryTab", {
                    selectedProduct: item,
                  });
                }}
              >
                <View
                  style={{
                    backgroundColor: "white",
                    alignItems: "center",
                    padding: 3,
                    elevation: 4,
                    borderRadius: 10,
                    margin: 6,
                  }}
                >
                  <View>
                    <Image
                      source={{ uri: item.image }}
                      style={{
                        height: productCardWidth,
                        width: productCardWidth,
                        borderRadius: 10,
                        marginBottom: 5,
                        zIndex: 1,
                      }}
                    />

                    <View
                      style={{
                        alignItems: "center",
                        justifyContent: "center",
                        height: productCardWidth,
                        width: productCardWidth,
                        position: "absolute",
                        backgroundColor: Colors.lightGray,
                        borderRadius: 10,
                        marginBottom: 5,
                        zIndex: 0,
                      }}
                    >
                      <ActivityIndicator
                        color={Colors.accentColor}
                        size={"small"}
                        style={{
                          top: 10,
                          right: 10,
                          position: "absolute",
                        }}
                      />
                      <FontAwesome5
                        name={"image"}
                        size={26}
                        color={"black"}
                        style={
                          {
                            // position: "absolute",
                          }
                        }
                      />
                    </View>
                  </View>
                  <Text
                    style={{
                      color: Colors.dark,
                      fontWeight: "bold",
                      fontSize: 16,
                    }}
                  >
                    {item.title.length > 12
                      ? item.title.slice(0, 12) + "..."
                      : item.title}
                  </Text>
                  <Text
                    style={{
                      fontWeight: "bold",
                    }}
                  >
                    {item.price} {item.currency}
                  </Text>
                </View>
              </TouchableWithoutFeedback>
            );
          }}
        />
      </View>
    </View>
  );
}

That should be it. Do upvote my solution if it worked for you or provide you with the idea to fix your solution.

Add comments if you have any queries regarding the same. Happy to help!

Upvotes: 1

Related Questions