How do I pass data to one screen and then pass it to another one using react navigation?

Viewed 20

I have 4 buttons on one Screen1 that pass different data to Screen2. The data received in Screen2 has to be sent to Screen3 again using react navigation. I am aware of passing parameters using react-navigation along a route but how do I pass that same data from Screen2 to Screen3 again using an if statement? I am very new to react native so any help would be appreciated

1 Answers
const Screen1 = () => {
  const navigation = useNavigation()
          
  const onPress = () => {              
    navigation.navigate("Screen2", {
      thing1:"my thing",
      thing2:"my second thing"
    })
  }
}
            
                 
const Screen2 = ({ route }) => {
   const navigation = useNavigation()
  
  // get the params
  const { thing1, thing2 } = route.params

 const onPress = () => {
  // send to screen 3
  navigation.navigate("Screen3", {
    thing1,
    thing2
  })
 }
}

EDIT Oh - i think i realised what you meant by an 'if statement'. You are talking about an effect when you land on the page.

I would say that navigating automatically away from a page is very likely to cause you problems, and may mean you need to combine your screens into one. But to do it you would use an effect:

const Screen1 = () => {
  const navigation = useNavigation()
          
  const onPress = () => {              
    navigation.navigate("Screen2", {
      thing1:"my thing",
      thing2:"my second thing"
    })
  }
}
            
                 
const Screen2 = ({ route }) => {
   const navigation = useNavigation()
   const isFocused = useIsFocused() // react-navigation
  // get the params
  const { thing1, thing2 } = route.params

 useEffect(() => {
  if(thing2 !== thing1 && isFocused){
    navigation.navigate("Screen3", {
      thing1,
      thing2
    })
  }
 }, [thing1, thing2, isFocused]) // <- this means the callback will trigger whenever one changes, including when the component gains focus from react-navigation

}
Related