How to truncate 'back' button for headerTitle in react-navigation?

Viewed 1492

I'm using react-navigation with StackNavigator. Is there a way to avoid the overlapping of the back button label and the headerTitle by truncating the back button label?

const MainNavigationOptions = {
    headerStyle: {
        backgroundColor: colors.CiPrimary
    },
    headerTitleStyle: {
        color: 'white',
        height: 50,
        width: 140
    },
    headerTintColor: 'white',
    headerTitle:
    <Text>LONG TEXT FOR TESTING</Text>
}

Illustration of issue:

Overlapping of back button and header title

3 Answers

(This Answer takes into account that the viewer is using react-navigation 5.x)

In Your Screen component

export const screenOptions = (navData) => {
  let title = navData.route.params.movieTitle;
  if (title.length > 18) {
    title = title.substr(0, 18) + "...";
  }
  return {
    headerTitle: title,
  };
};

Here, since we are using substr() , you can use it accordingly and truncate it to custom match your case, keeping in mind the edge cases.

Then you can import it in your AppNavigator.js or wherever you initialize your navigator (in my case below ;)

import {screenOptions as MoviesDetailScreenOptions} from
"../screens/MovieDetailScreen";

Here screenOptions is the named-export you are using MoviesDetailScreenOptions is the alias if i am not mistaken.

If you mean to shorten the back button label, why not use either:

  • headerBackTitle (change the Back label for the previous screen, put it in navigationOptions of the previous screen);
  • headerBackTitleStyle (change the Back label displayed on current screen, put it in navigationOptions of the current screen)
Related