BobiSad
BobiSad

Reputation: 69

Best way to set header title from a functional component?

I have a functional component and I want to set the header title from the inside, while still being able to pass a function from inside the component as a parameter to the header.

The component is in a StackNavigator.

const generateStackOptions: ({ navigation, screenProps}: any) => NavigationScreenOptions = ({
    navigation,
    screenProps
}: any): NavigationScreenOptions => {
    const title :any = navigation.getParam("title", null);
    return {
        title
    };
};

const stackNavigatorConfig: StackNavigatorConfig = {
    initialRouteName: Routes.Info,
    navigationOptions: generateStackOptions
};

export const stackNavigator: NavigationContainer = createStackNavigator(stackRoutes, stackNavigatorConfig);

This approach does not work:

const Info: NavigationScreenComponent = (props: Props) => {
    const data = [];
    const myFunctionIDefineHere = () => {
      // Populates the data. This function should be called from a button in the header.
    }
    Info.navigationOptions = {
        title: "This is the information page"
    }
};

When the navigator accesses the navigationOptions it is still empty / undefined.

This approach however, does work:

const Info: NavigationScreenComponent = (props: Props) => {
   const data = [];
   const myFunctionIDefineHere = () => {
      // Populates the data. This function should be called from a button in the header.
   }
};

Info.navigationOptions = {
    title: "This is the information page"
};

But there is a function inside the component I cannot access now, which I need to add to the header. What's the best approach to this?

Upvotes: 1

Views: 652

Answers (1)

Vladimir
Vladimir

Reputation: 21

You may use something like this:

const Info: NavigationScreenComponent = (props: Props) => {
   const data = [];
   const myFunctionIDefineHere = () => {
     // Populates the data. This function should be called from a button in    the header.
   }
   props.navigation.setParams({titleParam: "Your new text"});

};  

Info.navigationOptions = screenProps => ({
  title: screenProps.navigation.getParam("titleParam", "You title text")
});

I believe it's possible;e to pass a function as well.

Upvotes: 2

Related Questions