Home > front end >  Passing state through navigation parameter react native
Passing state through navigation parameter react native

Time:09-22

Ive got the state: const [isPressed, setIsPressed] = useState(false) Then I want to pass the setIsPressed when navigating to another sreen, which i wrote: On the from Screen: onPress{() => navigation.navigate('Map', {setIsPressed})} On the to Screen: onPress={() => {navigation.navigate('DM'); setIsPressed(true);}}

However, I get an error saying 'setIsPressed is not a function' when pressing on the To Screen button

How do I fix this?

CodePudding user response:

This is the way you can do it, here is you first screen:

const togglePressed = () => setIsPressed(prev=>!prev);



onPress={() =>
   navigation.navigate('ScreenName', {
     onRefreshParent: () => togglePressed(),
   })
}

And in you other screen use it like this:

 onPress={() => route.params.onRefreshParent && route.params.onRefreshParent()}

CodePudding user response:

There are two pieces to this: 1. Pass params to a route by putting them in an object as a second parameter to the navigation.navigate function: navigation.navigate('RouteName', { /* params go here */ }). 2. Read the params in your screen component: route.params.

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => {
          /* 1. Navigate to the Details route with params */
          navigation.navigate('Details', {
            itemId: 86,
            otherParam: 'anything you want here',
          });
        }}
      />
    </View>
  );
}

function DetailsScreen({ route, navigation }) {
  /* 2. Get the param */
  const { itemId, otherParam } = route.params;
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
      <Text>itemId: {JSON.stringify(itemId)}</Text>
      <Text>otherParam: {JSON.stringify(otherParam)}</Text>
      <Button
        title="Go to Details... again"
        onPress={() =>
          navigation.push('Details', {
            itemId: Math.floor(Math.random() * 100),
          })
        }
      />
      <Button title="Go to Home" onPress={() => navigation.navigate('Home')} />
      <Button title="Go back" onPress={() => navigation.goBack()} />
    </View>
  );
}

https://snack.expo.dev/

  • Related