How to call a class function from inside a React Navigation Header Ba

Viewed 1219

I am trying to call a parameterized function in a header but could not as I am unable to find to way to pass parameter.

class MyScreen extends React.Component {

static navigationOptions = ({ navigation }) => 
{
    headerLeft: (
        <SearchBar 
         placeholder="Search"
         round
         onChangeText={text => this.searchFunction(text)}
        />
    )
};

*searchFunction(text) 
{
    alert( text + ' searched succesfully');
}*

componentDidMount() 
{
  **//I would need implementation here**
}

render() 
{
    return (<View />);
}

}
1 Answers

The reserved word this means nothing in the static context of the navigationOptions function, So you can't use it there to call the searchFunction.

There's a way to add params to the navigation object so you can get them in the navigationOptions static function.

You can add the searchFunction as a navigation object param and pass it to the onChangeText attribute.

The implementation looks like this:

class MyScreen extends React.Component {

  // Pass the searchFunction from the navigation params to the `onChangeText` attribute.
  // It should be triggered with the `text` argument. 
  static navigationOptions = ({ navigation }) => 
  {
    headerLeft: (
      <SearchBar 
       placeholder="Search"
       round
       onChangeText={navigation.getParam('searchFunc')} 
      />
    )
  };

  // Use arrow function to bind it to the MyScreen class.
  // (I'm not sure you have to do it like this, try to use it as a normal function first)
  searchFunction = (text) => {
    alert( text + ' searched succesfully');
  }

  // Add the `searchFunction` as a navigation param:
  componentDidMount() {
    this.props.navigation.setParams({searchFunc: this.searchFunction})
  }

  // Since we pass a class function as a param
  // I believe it would be a good practice to remove it 
  // from the navigation params when the Component unmounts.
  componentWillUnmount() {
    this.props.navigation.setParams({searchFunc: null})
  }

  render() {
    return (<View />);
  }
}

Source

Related