I am trying to change the badge of the tabNavigator from navigationOptions dynamically in React Native.
I am trying to change it with setState, but it is not updating.
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
postsBadgeCount: 0,
progressBadgeCount: 0
};
this.Apps = this.startApp();
}
componentDidMount() {
setInterval(() => {
this.setState({ progressBadgeCount: this.state.progressBadgeCount + 1 });
console.log('change state', this.state.progressBadgeCount);
}, 5000);
}
startApp() {
const BottomNav = createMaterialBottomTabNavigator({
Progress: {
screen: stack2,
navigationOptions: {
tabBarLabel: 'Progress',
tabBarIcon: ({ tintColor }) => (
<View>
<IconFA name="calendar-check-o" size={22} color={tintColor} />
{this.state.progressBadgeCount > 0 ?
<View style={style.badge}>
<Text style={style.badgeCount}>1</Text>
</View> : undefined}
</View>
)
}
},
{
...
});
const navigator = createSwitchNavigator(
...
);
return createAppContainer(navigator);
}
render() {
return (
<this.Apps/>
);
}
}
When I am trying to update the progressBadgeCount using setState, it doesn't change on UI.
Any suggestions on how to update the badge count in this situation?
Thank you
startApp() is running only once, in the constructor. Rather than saving it into this.Apps, you could change your render() to:
render() {
return this.startApp();
}
This way it runs startApp() on each rerender.
Related
I want add button in react-native header , the button is to mas and unmask password in the page, the problem on click when i change the state to change secureTextEntry value, the icon wont change will keep as the initial value;
the function is working fine but the icon cant change
this.state.secureTextEntry ? "eye" : "eye-slash"
this is the main code
class ChangePasswordScreen extends Component {
constructor(props) {
super(props);
this.state = {
newPassword: null,
currentPassword: null,
confirmPassword: null,
errors: [],
secureTextEntry: true
};
this.maskPassword = this.maskPassword.bind(this)
}
componentDidMount() {
this.props.navigation.setParams({
headerRight: ( < TouchableOpacity onPress = {
() => {
this.maskPassword();
}
} > < Icon style = {
styles.eyeIcon
}
name = {
this.state.secureTextEntry ? "eye" : "eye-slash"
}
size = {
20
}
color = {
Colors.WHITE
}
/></TouchableOpacity > )
})
}
static navigationOptions = ({
navigation
}) => {
return {
// headerTitle: <LogoTitle />,
headerRight: navigation.state.params && navigation.state.params.headerRight,
};
};
maskPassword = () => {
this.setState({
secureTextEntry: !this.state.secureTextEntry
})
}
}
Kinda late, might help someone nevertheless.
If you wish to add a button to the header of a screen, from the screen itself, not the App.js file and you are using a functional component, it goes like this:
import { useNavigation } from '#react-navigation/native'
export default function () {
const nav = useNavigation();
useEffect(() => {
nav.setOptions({
headerRight: () => <Button />,
});
}
}
The problem is this.setState will not re-render header component . if you want to change header right then you have to call setParams again
Try this code in componentDidMount
componentDidMount() {
this.props.navigation.setParams({
headerRight: this.setHeaderRight(this.state.secureTextEntry)
});
}
Set function for header right
setHeaderRight = state => {
//console.log("setHeaderRight", this.state.secureTextEntry);
return (
<TouchableOpacity
onPress={() => {
this.maskPassword();
}}
>
<Icon
style={styles.eyeIcon}
name={state ? "eye" : "eye-slash"}
size={20}
color={Colors.WHITE}
/>
</TouchableOpacity>
);
};
Set header right again when state set
maskPassword = () => {
this.setState({
secureTextEntry: !this.state.secureTextEntry
});
this.props.navigation.setParams({
headerRight: this.setHeaderRight(!this.state.secureTextEntry)
});
};
You are setting a Component as a navigation param on Component mount and passing in a state value at the time the Component mounted.
This param never gets changed or updated again so the navigation header never gets re rendered.
A better way would be to pass the value of state directly as a navigation param and use that in the component that is used directly in the navigationOptions
I have an AuditionsList component which displays a FlatList. In a different reducer I'm changing Settings called location and roleType. Depending on these new settings I want to refresh the AuditionList.
Here is my code:
import React from 'react';
import { Text, View, FlatList, ActivityIndicator } from 'react-native';
import { connect } from 'react-redux';
import AuditionItem from './AuditionItem';
import Auditions from './../data/Auditions';
class AuditionsList extends React.Component {
constructor(props) {
super(props);
this.state = { isLoading: true, data: [], refresh: false }
}
componentDidMount() {
this._refreshData();
}
_onRefresh() {
this.setState({ isLoading: true }, this._refreshData() );
}
_refreshData = () => {
Auditions.fetchAuditions(this.props.productionType, this.props.location, this.props.roleType).then(auditions => {
this.setState({ isLoading: false, data: this._addKeysToAuditions(auditions) });
});
}
_addKeysToAuditions = auditions => {
return auditions.map(audition => {
return Object.assign(audition, { key: audition.Role});
});
}
_renderItem = ({ item }) => {
return (
<AuditionItem
auditionId={item.objectId}
role={item.Role}
project={item.Project.Name}
productionType={item.Project.ProductionType.Type}
auditionDate={JSON.stringify(item.Date.iso)}
productionHouse={item.Project.ProductionHouse.Name}
/>
);
}
render() {
console.log("Here...");
if (this.state.isLoading) {
return (
<View style={{flex: 1, paddingTop: 20}}>
<ActivityIndicator />
</View>
);
}
return (
<View style={{ flex: 1 }}>
<FlatList onRefresh={() => this._onRefresh()} refreshing={this.state.isLoading} data={this.state.data} renderItem={this._renderItem} />
</View>
);
}
}
const mapStateToProps = state => {
return {
location: state.settings.location,
roleType: state.settings.roleType,
};
}
export default connect(mapStateToProps)(AuditionsList);
I need to call the _onRefresh() or _refreshData() function AFTER the callback to mapStateToProps (which runs successfully) but BEFORE the FlatList re-renders (which also happens successfully, but with old data). So where do I call the _onRefresh() or _refreshData() functions? Putting them in render() causes an infinite loop.
Have you tried using the ComponentDidUpdate react lifecycle method? This will fire after you receive new props, and you could make a call to this._refreshData there.
https://reactjs.org/docs/react-component.html#componentdidupdate
I have a button in header to open & close navigation drawer menu.
When I call below method from componentDidMount() it worked and opened the menu:
this.props.navigation.toggleDrawer();
But when I click the button it didn't work and just fade the screen!
Here is the component code :
export class Home extends BaseScreen {
constructor(props) {
super(props);
}
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return ({
headerStyle: {
backgroundColor: '#FF9800'
}
, headerRight: <UserCoins />
, headerLeft: <Button onPress={params.handlePress} title='Menu' />
, title: 'title'
})
}
_handlePress() {
this.props.navigation.toggleDrawer();
}
state = {
coins: 0,
}
//
componentDidMount() {
this.props.navigation.setParams({
handlePress: this._handlePress.bind(this)
});
//here working
this.props.navigation.toggleDrawer();
}
render() {
return (<Text />);
}
}
export default Home
My navigator structure is :
1.SwitchNavigator
2.BottomTabNavigator
3.DrawerNavigator
4.StackNavigator (Home component inside it)
You can call 'navigation' that you are passing into your static NavigationOptions rather than trying to bind it in the params for navigation.
Try this on your onPress Event for your button
onPress={() => navigation.navigate('DrawerToggle')}
I have 2 classes: my default class HomeScreen used for the home page and another class MyList which I use to generate a flatlist on my HomeScreen.
My problem is that I do not succeed in building my navigation function in my MyList class.
I always get the following error: "Can't find variable: navigate".
I took a look at this Calling Navigate on Top Level Component but I really don't know how to implement it in my code.
Here's what I've tried:
class MyList extends React.Component {
_keyExtractor = (item, index) => item.note.id;
_renderItem = ({ item }) => (
<TouchableNativeFeedback
onPress={() => navigate('Note', { noteId: item.note.id })} >
<View>
<Text style={styles.noteElementTitle} >{item.note.title}</Text>
<Text style={styles.noteElementBody} >{item.note.body}</Text>
</View>
</TouchableNativeFeedback>
);
render() {
return (
<FlatList
data={this.props.data}
keyExtractor={this._keyExtractor}
renderItem={this._renderItem}
/>
);
}
}
export default class HomeScreen extends React.Component {
static navigationOptions = {
title: 'Notes',
headerStyle: { backgroundColor: 'rgb(255, 187, 0)' },
headerTitleStyle: { color: 'white' },
};
render() {
const { navigate } = this.props.navigation;
return (
<MyList
data={this.state.data}
load={this.state.load}
navig={this.props.navigation}
>
</MyList>
);
}
}
const Project = StackNavigator({
Home: { screen: HomeScreen },
NewNote: { screen: NewNoteScreen },
Note: { screen: NoteScreen }
});
AppRegistry.registerComponent('Project', () => Project);
Thanks for your help.
Because your MyList component is not part of your stack the navigation prop is not available for that.
You have 2 options.
First option you can pass the navigation prop manually to MyList
render() {
const { navigate } = this.props.navigation;
return (
<MyList
data={this.state.data}
load={this.state.load}
navigation={this.props.navigation}
>
</MyList>
);
}
Second option you can use withNavigation.
withNavigation is a Higher Order Component which passes the navigation
prop into a wrapped Component. It's useful when you cannot pass the
navigation prop into the component directly, or don't want to pass it
in case of a deeply nested child.
import { Button } 'react-native';
import { withNavigation } from 'react-navigation';
const MyComponent = ({ to, navigation }) => (
<Button title={`navigate to ${to}`} onPress={() => navigation.navigate(to)} />
);
const MyComponentWithNavigation = withNavigation(MyComponent);
I have a scene:
<Scene key="myFeed" component={myFeed} renderTitle={level}/>
In which I use the component to display the "title".
This function:
const level = () => {
return (
<Level/>
)
}
This component:
export class Level extends Component {
constructor(props) {
super(props);
this.state = {
progressBar: {},
loading: true,
};
}
connection() {
myApi.getServer('/user/level/', (data) => {
this.setState({loading: false, progressBar: data});
}, (err) => {
console.log(err.message);
this.setState({loading: false});
})
}
render() {
return(
<View style={styles.topBarCenterSlider}>
<View style={styles.topBarSlider}>
<View style={[styles.topBarStatus, {width: this.state.progressBar.level["progress"] + '%' : 0}]}/>
</View>
</View>
</View>
);
}
}
I need to change the component after the server response.
Help please, and sorry for my English))
I see you dont invoke "connection()". Put in componentWiLlMount
componentWillMount() {
this.connection();
}