Home > Blockchain >  How can i pass a function to the navigation ( stack ) component
How can i pass a function to the navigation ( stack ) component

Time:02-26

so I wanted to pass the savedLocationHandler() function to the navigation component so I can put it on the Header button because i guess that's the only way to access the header but I didn't know how to do that ! i tried setParams and it didn't work , I only know the route method but that's only used from a screen to another i guess ?!

import React, { useCallback, useEffect, useState } from "react";
import { Button, StyleSheet, Text, View } from "react-native";
import MapView, { Marker } from "react-native-maps";

const MapScreen = ({ navigation }) => {
  const [selectedLocation, setSelectedLocation] = useState();
  const MapRegion = {
    latitude: 37.78,
    longitude: -122.43,
    latitudeDelta: 0.0922,
    longitudeDelta: 0.0421,
  };
  const selectLocationHandler = (event) => {
    console.log(event);
    setSelectedLocation({
      lat: event.nativeEvent.coordinate.latitude,
      lng: event.nativeEvent.coordinate.longitude,
    });
  };
  let markerCoordinates;

  const savedLocationHandler = () => {
    if (!selectedLocation) {
      return;
    }
    navigation.navigate("NewPlaceScreen", {
      selectedLocation: selectedLocation,
    });
  };

  if (selectedLocation) {
    markerCoordinates = {
      latitude: selectedLocation.lat,
      longitude: selectedLocation.lng,
    };
  }

  return (
    <MapView
      style={styles.mapImage}
      region={MapRegion}
      onPress={selectLocationHandler}
    >
      {markerCoordinates && (
        <Marker title="Picked Location" coordinate={markerCoordinates}></Marker>
      )}
    </MapView>
  );
};  

and this is the navigation component ( only where i want to pass the function )

<Stack.Screen
          name="MapScreen"
          component={MapScreen}
          options={({ navigation }) => ({
            headerRight: () => (
              <TouchableOpacity
                onPress={() => { {/* i want to pass the function here*/ } 
                  saveFn;
                }}
                style={{ marginHorizontal: 20 }}
              >
                <Text
                  style={{
                    fontSize: 19,
                    fontWeight: "bold",
                    color: Platform.OS === "android" ? "#C06E00" : "white",
                  }}
                >
                  Save
                </Text>
              </TouchableOpacity>
            ),
          })}
        />
      </Stack.Navigator>

CodePudding user response:

We could provide a function for the headerRight prop for any screen using the useLayoutEffect as follows.

const MapScreen = ({ navigation }) => {

...


useLayoutEffect(() => {
    navigation.setOptions({
      headerRight: () => console.log("DO SOMETHING")
    })
}, [])

...

}

  • Related