Reputation: 3777
I'm using the react-native-material-bottom-navigation package for my app. But whenever I call setState
, even if I don't even pass a new state change, the bottom navigation resets to the first tab. What is causing this? The example code works just fine but as soon as I throw in setState
it messes up.
Example code:
import React, { Component } from 'react'
import BottomNavigation, { Tab } from 'react-native-material-bottom-navigation'
import Icon from 'react-native-vector-icons/MaterialIcons'
class MyComponent extends Component {
render() {
return (
<BottomNavigation
labelColor="white"
rippleColor="white"
style={{ height: 56, elevation: 8, position: 'absolute', left: 0, bottom: 0, right: 0 }}
onTabChange={(newTabIndex) => alert(`New Tab at position ${newTabIndex}`)}
>
<Tab
barBackgroundColor="#37474F"
label="Movies & TV"
icon={<Icon size={24} color="white" name="tv" />}
/>
<Tab
barBackgroundColor="#00796B"
label="Music"
icon={<Icon size={24} color="white" name="music-note" />}
/>
<Tab
barBackgroundColor="#5D4037"
label="Books"
icon={<Icon size={24} color="white" name="book" />}
/>
<Tab
barBackgroundColor="#3E2723"
label="Newsstand"
icon={<Icon size={24} color="white" name="newspaper" />}
/>
</BottomNavigation>
)
}
}
Upvotes: 0
Views: 640
Reputation: 287
If you call this.setState()
in a React Component, it will re-render itself. This means that BottomNavigation
will be reset to its default state, if you don't tell it which state it should show.
The default state of the Bottom Navigation is to set the first Tab to active.
You can define the state of the Bottom Navigation using the activeTab
prop.
class MyComponent extends Component {
state = { activeTab: 0 }
handleTabChange = (newTabIndex) => {
this.setState({ activeTab: newTabIndex })
}
render() {
return (
<BottomNavigation
activeTab={this.state.activeTab}
onTabChange={this.handleTabChange}
>
<Tab
barBackgroundColor="#37474F"
label="Movies & TV"
icon={<Icon size={24} color="white" name="tv" />}
/>
{/* Skipped Tabs for brevity */}
</BottomNavigation>
)
}
}
This will keep the Bottom Navigation in its current state even after a re-render.
An example can also be found in react-native-material-bottom-navigation/examples.
Upvotes: 1