I am trying to make dynamic tab.screen. my code is like this:
import React from 'react';
import { Text, View, TouchableOpacity, Modal } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import Icon from 'react-native-vector-icons/FontAwesome5';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Home from '../mainscreen/GeneralScreen';
import Core from '../mainscreen/CoreScreen';
import Docs from '../mainscreen/GeneralScreen';
import ESS from '../mainscreen/CoreScreen';
import General from '../mainscreen/GeneralScreen';
import HR from '../mainscreen/CoreScreen';
import Payroll from '../mainscreen/GeneralScreen';
import Server from '../mainscreen/CoreScreen';
const Tab = createBottomTabNavigator();
const tabcomponents = {
"Home" : Home,
"Core" : Core,
"Docs" : Docs,
"ESS" : ESS,
"General" : General,
"HR" : HR,
"Payroll" : Payroll,
"Server" : Server
};
class TabNavigator extends React.Component {
constructor() {
super();
this.state = {
dashboardtab:[],
}
this.tabnavigatorasync();
}
tabnavigatorasync = async () => {
try {
const dashboardtab = await AsyncStorage.getItem('dashboardtab');
const dashboardtabParse = JSON.parse(dashboardtab);
this.setState({dashboardtab: dashboardtabParse});
} catch (error) {
}
}
render(){
const tabnavigatorRender = this.state.dashboardtab.map((item, index) => {
const tabcomponentsrender = tabcomponents[item.admintab.label];
return <Tab.Screen name={item.admintab.label} component={tabcomponentsrender} key={index}/>
});
return(
<Tab.Navigator>
{tabnavigatorRender}
</Tab.Navigator>
)
}
}
export default TabNavigator;
the result appears an error like this:
Error: Couldn't find any screens for the navigator. Have you defined any screens as its children?
is there something wrong with the code i made?
As the error states you are not having any screens inside the TabNavigator.
When the component is mounted the array is empty and the data is loaded later.
So you can fix this like below
render(){
const tabnavigatorRender = this.state.dashboardtab.map((item, index) => {
const tabcomponentsrender = tabcomponents[item.admintab.label];
return <Tab.Screen name={item.admintab.label} component={tabcomponentsrender} key={index}/>
});
// Add this to return null or you can also show <ActivityIndicator/>
if(this.state.dashboardtab.length===0)
return null;
return(
<Tab.Navigator>
{tabnavigatorRender}
</Tab.Navigator>
)
}
Also call the tabnavigatorasync from componentDidMount instead of calling it from the constructor.
componentDidMount(){
this.tabnavigatorasync();
}