David Schumann
David Schumann

Reputation: 14793

Dynamically enable/disable tabs in react navigation TabNavigator

I have a fairly big mixture of nested Stack- and TabNavigators in my App.

What I want to do is change the number of tabs through some view that is a few Navigators inside the app.

I am currently passing the information whether a certain Tab should be displayed on startup like so:

const RootNav = RootNavigator(this.state.tabShouldBeEnabled);

return (
  <View style={styles.mainContainer}>
    <RootNav />
  </View>

My RootNavigator passes this information on until the TabNavigator is reached, and the tab is displayed or not.

const RootNavigator = (userLoggedIn: boolean, coachEnabled: boolean) =>
  StackNavigator(
    {
    ...
    });

To change the state of my main Component I was considering handing down a state change callback in a similar fashion. But now I am wondering whether there is a cleaner way than converting all the components on the way into functions which only serve the purpose of returning a component with the state change function passed on.

Upvotes: 2

Views: 2615

Answers (1)

Aafaq Ahmad
Aafaq Ahmad

Reputation: 321

You can do this by conditional rendering.

class ControlledTabs extends React.Component {
constructor(props, context) {
super(props, context);

this.handleSelect = this.handleSelect.bind(this);
this.nextTab = this.nextTab .bind(this);

this.state = {
  key: 1
};
}

nextTab (key){
 this.setState({key:key})
}

handleSelect(key) {
 alert(`selected ${key}`);
 this.setState({ key });
}

render() {
let tab1 = <Tab eventKey={1} title="Tab 1">Tab 1 content</Tab>;
let tab2 = <Tab eventKey={2} title="Tab 2" disabled>Tab 2 content</Tab>;      
let tab3 = <Tab eventKey={3} title="Tab 3" disabled>Tab 3 content</Tab>;

if(this.state.key == 2){
  tab2 = <Tab eventKey={2} title="Tab 2">Tab 2 content</Tab>;
  tab3 = <Tab eventKey={3} title="Tab 3" disabled>Tab 3 content</Tab>;
}
 if(this.state.key == 3){
  tab2 = <Tab eventKey={2} title="Tab 2">Tab 2 content</Tab>;      
  tab3 = <Tab eventKey={3} title="Tab 3">Tab 3 content</Tab>;
}

return (
  <Tabs
    activeKey={this.state.key}
    onSelect={this.handleSelect}
    id="controlled-tab-example"
  >
    {tab1}
    {tab2}
    {tab3}
    <button onClick={()=>this.nextTab(2)} value="next">Next 2</button>
    <button onClick={()=>this.nextTab(3)} value="next">Next 3</button>

  </Tabs>
);
}
}

Upvotes: 1

Related Questions