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.
Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don't work inside classes — they let you use React without classes. (We don't recommend rewriting your existing components overnight but you can start using Hooks in the new ones if you'd like.)
You can set buttons in the header through the headerLeft and headerRight properties in options . The back button is fully customizable with headerLeft , but if you just want to change the title or image, there are other options for that — headerBackTitle , headerBackTitleStyle , and headerBackImageSource .
useNavigation is a hook and hooks can only be used inside a functional component like this. But as you are using the class component so you can navigate like this. But you have to make sure that navigation prop is available in your class component by putting console.
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>
)
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With