React Navigation Header in Functional Components with Hooks

esfoobar picture esfoobar · Apr 17, 2019 · Viewed 11.4k times · Source

I am trying to inject custom headers to React functional components that are using Hooks.

So for example I have the following React functional component with some hooks:

function StoryHome(props) {
  const [communityObj, setCommunityObj] = useState({
    uid: null,
    name: null,
  });
...
}

StoryHome.navigationOptions = {
  title: 'Stories',
  headerTitleStyle: {
    textAlign: 'left',
    fontFamily: 'OpenSans-Regular',
    fontSize: 24,
  },
  headerTintColor: 'rgba(255,255,255,0.8)',
  headerBackground: (
    <LinearGradient
      colors={['#4cbdd7', '#3378C3']}
      start={{ x: 0, y: 1 }}
      end={{ x: 1, y: 1 }}
      style={{ flex: 1 }}
    />
  ),
  headerRightContainerStyle: {  
    paddingRight: 10,   
  },    
  headerRight: (    
    <TouchableOpacity onPress={navigation.navigate('storiesList')}> 
      <Ionicons 
         name="ios-search-outline"  
         size={25}  
         color="white"  
         left={20}  
       />   
    </TouchableOpacity>
  )
};

export default StoryHome;

So this sort of works, except with the TouchableOpacity part.

First, I don't get the Ionicon to render correctly and second, I don't have access to the navigation object outside of the functional component.

I would love to continue using Hooks but can't seem to figure this one out.

Answer

Tholle picture Tholle · Apr 17, 2019

navigationOptions can be a function that gets an object as argument with navigation as a property.

You also need to make sure you give a function to onPress, and that you don't invoke navigation.navigate directly.

StoryHome.navigationOptions = ({ navigation }) => ({
  title: "Stories",
  headerTitleStyle: {
    textAlign: "left",
    fontFamily: "OpenSans-Regular",
    fontSize: 24
  },
  headerTintColor: "rgba(255,255,255,0.8)",
  headerBackground: (
    <LinearGradient
      colors={["#4cbdd7", "#3378C3"]}
      start={{ x: 0, y: 1 }}
      end={{ x: 1, y: 1 }}
      style={{ flex: 1 }}
    />
  ),
  headerRightContainerStyle: {
    paddingRight: 10
  },
  headerRight: (
    <TouchableOpacity onPress={() => navigation.navigate("storiesList")}>
      <Ionicons name="ios-search" size={25} color="white" left={20} />
    </TouchableOpacity>
  )
});