setParams not working in react-native

Viewed 2321

I am using react-native with redux. I am trying to update current screen's params so that they can be accessed in a component used in top-bar but parameter is not getting set. My code is following:

Screen Route:

AlertNameForm: {
    screen: AlertNameForm,
    navigationOptions: ({navigation}) => CancelAndDone(navigation)
  }

Component Screen: In componentDidMount I am setting parameter.

class AlertNameForm {
    ..........
    componentDidMount() {
    this.props.navigation.setParams({onDonePress: this.onDonePress})
    }

    onDonePress: () => {
      // want to access this function in top-bar buttons.
    }
}

Following is further components:

export const CancelAndDone = (navigation) => ({
    headerLeft: <ButtonCancel navigation={navigation} />,
    headerRight: <ButtonDone navigation={navigation} />
})

const ButtonDone = withTheme(({navigation, theme: { tertiaryColor } }) => (
  <Button color={tertiaryColor} title="Done" onPress={() => {
      if (navigation.state.params && navigation.state.params.onDonePress) {
        navigation.state.params.onDonePress()
      }
      else {
        navigation.dispatch(NavigationActions.back())
      }
    }} />
))

But in ButtonDone component I am not able to access function onDonePress Is there any other way to setParams for current screen in react-native.

2 Answers

You should reference navigation.state.paramsusing this.props since navigation should be passed as a prop to that component.

You can assign the function within the target component as follows:

componentDidMount = () => {
   const { navigation } = this.props
     navigation.setParams({
        onDonePress: () => this.myFunction(),
     })
}

myFunction = () => { /*body function*/ }

In your header or footer component call:

navigation.state.params.onDonePress or route.params.onDonePress if you using React Navigation v5.

Related