Pass data from a Screen back to the Navigator in react-navigation v6

793 Views Asked by At

I have a screen which can be called by two different navigators, something like the following:

const DataScreen = ( { navigation } ) => {
  // this is the data produced inside the component and that I want to pass back to the parent navigator.
  const data = { data: "someData" };
  navigation.goBack();
}

const Stack1 = createStackNavigator();

const Stack1Navigator = () => {
  // the data produced in dataScreen should be handled in the "way 1" here
  return <Stack1.Navigator>
    <Stack1.Screen name='dataScreen' component={DataScreen} />
  </Stack1.Navigator>
}

const Stack2 = createStackNavigator();

const Stack2Navigator = () => {
  // the data produced in dataScreen should be handled in the "way 2" here
  return <Stack2.Navigator>
    <Stack2.Screen name='dataScreen' component={DataScreen} />
  </Stack2.Navigator>
}

const RootStack = createStackNavigator();

const App = () => {
  return <RootStack.Navigator>
    <RootStack.Screen name='stack1' component={Stack1Navigator} />
    <RootStack.Screen name='stack2' component={Stack2Navigator} />
  </RootStack.Navigator>
}

Some data is produced by such screen and I want to pass such data back to the navigator. How can I pass the data back to the navigator with react-navigation v6 in order to handle it inside the navigator with a specific function?

I ask this question since the other way around (i.e. passing to the screen the function defined inside the navigator) is not allowed by react-navigation because not serializable.

Thanks in advance.

1

There are 1 best solutions below

2
Vu Phung On

You want to pass param when goBack from Stack2 to Stack1, right?

React-navigation v6 has support: https://reactnavigation.org/docs/params/#passing-params-to-a-previous-screen

Simple ex: https://snack.expo.dev/@pqv2210/q-74563374