Reputation: 645
I am using React Navigation Bar v5 and setting title in App.js but I want to change it dynamically when the screen is displayed.
I tried this.props.navigation.navigate('ExistStock', { title: 'WHATEVER' })
but it doesn't work as it was working in v4.
What are the correct ways to change the navigation bar title and background color?
Upvotes: 1
Views: 2537
Reputation: 21
componentDidMount() {
this.props.navigation.setOptions({
title: "Whatever"
});
}
This can be used add title at the screen or change the title accordingly.
componentDidMount() {
this.props.navigation.setOptions({
title:
this.state.count === 0
? 'Select items'
: `${this.state.count} items selected`,
});
});
}
Changing the title according to the state of the component.
Upvotes: 0
Reputation: 16334
You can do it at screenOptions just like you do in V4.
You will have to pass the parameters
navigation.navigate('Details', { id: item.id, name: item.name,color:item.color })
And in the navigator you can use it as the title and color
<Stack.Screen
name="Details"
component={Details}
options={({ route }) => ({
title: route.params.name,
headerStyle: {
backgroundColor: oute.params.color,
},
})}
/>
Upvotes: 1
Reputation: 655
Use useFocusEffect from React native navigation with navigation.setOptions to dynamically set the navigation options on render.
import React, {useCallback} from 'react';
import {useFocusEffect} from '@react-navigation/native';
const myFunctionalComponent = props => {
useFocusEffect(
useCallback(() => {
props.navigation.setOptions({
title: 'Whatever',
});
}, [props.navigation])
);
...
You can apply any of the options listed in the documentation https://reactnavigation.org/docs/headers/#setting-the-header-title
Upvotes: 0