React navigation state.params not working - react-native

It is not working. I tried everything. Nothing works. state.params is simply not there if you make an advanced app.
I have this problem with the react "navigation". It says in the manual that the params object should be there https://reactnavigation.org/docs/navigation-prop.html#state-the-screen-s-current-state-route But it isn't.
I set an id parameter like this in screen 1 when I link to screen 2:
<TouchableWithoutFeedback onPress={ ()=> this.props.navigation.navigate('FontsTab', { id: item.id }) } style={styles.listHeader} >
<View style={styles.listRowContainer}>
<View style={styles.listinside1Container}>
<Image style={styles.listImage} source={item.icon} />
<View style={styles.listContainer} onPress={(event) => this._selectedItem(item.text)} >
<Text style={styles.listHeader} >
{item.title}
</Text>
<Text style={styles.listValue} >{item.value}</Text>
<Image
style={{width: 50, height: 50}}
source={{uri: item.img}}
/>
</View>
</View>
</View>
</TouchableWithoutFeedback>
But it's not working. In screen 2 I can't use the state.params :
<ScrollView style={styles.container}>
<Text>{ JSON.stringify(this.props.navigation)}</Text>
<Text>TEST{ state.params }</Text>
<Image
style={{width: 150, height: 150}}
source={{uri: this.state.dataSource.img}}
/>
<Text style={styles.textStyle} >{this.state.dataSource.text}</Text>
</ScrollView>
state.params just returns nothing. What can I do about it?
The full class for screen2:
class Fonts extends Component {
constructor(props) {
super(props);
this.state = {
params: null,
selectedIndex: 0,
value: 0.5,
dataSource: null,
isLoading: true
};
this.componentDidMount = this.componentDidMount.bind(this);
}
getNavigationParams() {
return this.props.navigation.state.params || {}
}
componentDidMount(){
return fetch('http://www.koolbusiness.com/newvi/4580715507220480.json')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
...this.state,
isLoading: false,
dataSource: responseJson,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
render() {
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return (
<ScrollView style={styles.container}>
<Text>{ JSON.stringify(this.props)}</Text>
<Text>TEST{ this.state.params }</Text>
<Image
style={{width: 150, height: 150}}
source={{uri: this.state.dataSource.img}}
/>
<Text style={styles.textStyle} >{this.state.dataSource.text}</Text>
</ScrollView>
);
}
}
In my app this pain is reproducible by a simple button in screen1:
<Button
onPress={() => navigate('FontsTab', { name: 'Brent' })}
title="Go to Brent's profile"
/>
Then switching to the FontsTab works but the params are not in the state object:
I also have this code for the tabview
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { StackNavigator } from 'react-navigation';
import { Icon } from 'react-native-elements';
import FontsHome from '../views/fonts_home';
import FontsDetails from '../views/fonts_detail';
const FontsTabView = ({ navigation }) => (
<FontsHome banner="Fonts" navigation={navigation} />
);
const FontsDetailTabView = ({ navigation }) => (
<FontsDetails banner="Fonts Detail" navigation={navigation} />
);
const FontsTab = StackNavigator({
Home: {
screen: FontsTabView,
path: '/',
navigationOptions: ({ navigation }) => ({
title: '',
headerLeft: (
<Icon
name="menu"
size={30}
type="entypo"
style={{ paddingLeft: 10 }}
onPress={() => navigation.navigate('DrawerOpen')}
/>
),
}),
},
Detail: {
screen: FontsDetailTabView,
path: 'fonts_detail',
navigationOptions: {
title: 'Fonts Detail',
},
},
});
export default FontsTab;

this.props.navigation.state.params.id will give you the value of param id passed from screen1.

I put my screen in the right StackNavigator and then it worked.

Related

Add a button "see more" in FlatList?

I use flatList to make a list of elements. I would like to show 15 elements and then add a button "see more" to show the next 15 etc.
I was about tu use this tutorial : https://aboutreact.com/react-native-flatlist-pagination-to-load-more-data-dynamically-infinite-list/
But I don't need to use fetch, I already have set up the data (state.listData) and in fact, I'm a little lost on how to adapt it...
I thought that maybe anyone could help me a little.
Thanks a lot
this.state = {
selectedId: '',
setSelectedId:'',
listData:''
}
};
renderItem = ({ item }) => {
const backgroundColor = item.id === this.selectedId ? "transparent" : "fff";
return (
<View style={{flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center'}}>
<Item
item={item}
onPress={() => this.props.navigation.navigate('UpdateTripsForm')}
style={{ backgroundColor }}
/>
<Image source={require("../../assets/images/arrow.png")} style={{width: 15, height:15, justifyContent: 'center'}}/>
</View>
);
};
initListData = async () => {
let list = await getFlights(0);
if (list) {
this.setState({
listData: list
});
}
};
render() {
return (
<SafeAreaView style={styles.container}>
<FlatList
data={this.state.listData}
renderItem={this.renderItem}
maxToRenderPerBatch={15}
keyExtractor={(item) => item.id}
extraData={this.selectedId}
/>
<TouchableOpacity
style={styles.touchable2}
onPress={() => this.props.navigation.goBack()}
>
<View style={styles.view2}>
<Text style={styles.textimg2}>
{i18n.t("tripsform.action.back")}
</Text>
</View>
<Image
source={require("../../assets/images/btn-background.png")}
style={styles.tripsimg2}
/>
</TouchableOpacity>
</SafeAreaView>
);
};
}
I just tried this thanks to #Pramod 's answer :
const Item = ({ item, onPress, style }) => (
<TouchableOpacity onPress={onPress} style={[styles.flightsListitem, style]}>
<Text style={styles.h4}>{item.id}</Text>
</TouchableOpacity>
);
export default class FlightsList extends Component {
constructor(props) {
super(props);
this.state = {
selectedId: '',
setSelectedId:'',
listData:'',
page:1,
perPage:2,
loadMoreVisible:true,
displayArray:[]
}
};
renderItem = ({ item }) => {
const backgroundColor = item.id === this.selectedId ? "transparent" : "fff";
return (
<View style={{flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center'}}>
<Item
item={item}
onPress={() => this.props.navigation.navigate('UpdateTripsForm')}
style={{ backgroundColor }}
/>
<Image source={require("../../assets/images/arrow.png")} style={{width: 15, height:15, justifyContent: 'center'}}/>
</View>
);
};
initListData = async () => {
let list = await getFlights(0);
if (list) {
this.setState({
listData: list
});
}
};
componentDidMount(){
this.setNewData()
// console.log(tempArray)
}
setNewData(){
var tempArray=[]
if(this.state.listData.length == this.state.displayArray.length){
this.setState({
loadMoreVisible:false
})
}else{
for(var i=0; i<(this.state.page*this.state.perPage); i++){
tempArray.push(this.state.listData)
}
this.setState({
displayArray: tempArray,
loadMoreVisible:true
})
}
}
loadMore(){
this.setState({
page: this.state.page+1
},()=>{
this.setNewData()
})
}
async UNSAFE_componentWillMount() {
this.initListData();
}
render() {
return (
<ImageBackground
source={require("../../assets/images/background.jpg")}
style={styles.backgroundImage}
>
<Header
backgroundImage={require("../../assets/images/bg-header.png")}
backgroundImageStyle={{
resizeMode: "stretch",
}}
centerComponent={{
text: i18n.t("mytrips.title"),
style: styles.headerComponentStyle,
}}
containerStyle={[styles.headerContainerStyle, { marginBottom: 0 }]}
statusBarProps={{ barStyle: "light-content" }}
/>
<SafeAreaView style={styles.container}>
<FlatList
data={this.state.displayArray}
renderItem={this.renderItem}
keyExtractor={(item) => item.id}
extraData={this.selectedId}
/>
{this.state.loadMoreVisible == true?
<Button style={{width:'100%', height:10, backgroundColor:'green', justifyContent:'center', alignItems:'center'}}
title = 'load more'
onPress={()=>{this.loadMore()}}>
</Button>:null}
<TouchableOpacity
style={styles.touchable2}
onPress={() => this.props.navigation.goBack()}
>
<View style={styles.view2}>
<Text style={styles.textimg2}>
{i18n.t("tripsform.action.back")}
</Text>
</View>
<Image
source={require("../../assets/images/btn-background.png")}
style={styles.tripsimg2}
/>
</TouchableOpacity>
</SafeAreaView>
</ImageBackground>
);
};
}
the flatlist is not displayed : I get :
You can user pagination method with per page limit so that you can have granular control
Load the array per page when component mount
On every click increase the per page and based on per page update data of your flat list
And also put a flag which will check when the data has ended which will help to hide the load more button when data ends
Working example: https://snack.expo.io/#msbot01/suspicious-orange
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
SafeAreaView,
SectionList,
Switch,
FlatList
} from 'react-native';
import Constants from 'expo-constants';
import Icon from 'react-native-vector-icons/FontAwesome';
import AwesomeIcon from 'react-native-vector-icons/FontAwesome';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default class App extends Component<Props> {
constructor(props) {
super(props);
this.state = {
page:1,
perPage:2,
loadMoreVisible:true,
DATA: [{
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
title: 'First Item',
},
{
id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
title: 'Second Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'fourth Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'fifth Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29sd72',
title: 'sixth Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29dr72',
title: 'seventh Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d7w2',
title: 'Eight Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29ad72',
title: 'Nineth Item',
},
{
id: '58694a0f-3da1-471f-bd96-14557d1e29d72',
title: 'Tenth Item',
}],
displayArray:[]
}
}
componentDidMount(){
this.setNewData()
// console.log(tempArray)
}
setNewData(){
var tempArray=[]
if(this.state.DATA.length == this.state.displayArray.length){
this.setState({
loadMoreVisible:false
})
}else{
for(var i=0; i<(this.state.page*this.state.perPage); i++){
tempArray.push(this.state.DATA[i])
}
this.setState({
displayArray: tempArray,
loadMoreVisible:true
})
}
}
loadMore(){
this.setState({
page: this.state.page+1
},()=>{
this.setNewData()
})
}
render() {
return (
<View style={{ flex: 1 }}>
<FlatList
data={this.state.displayArray}
renderItem={({item})=>
<View style={{flexDirection:'row'}}>
<Text style={{fontSize:20}}>{item.title} </Text>
</View>
}
keyExtractor={item => item.id}
/>
{this.state.loadMoreVisible == true?
<View style={{width:'100%', height:10, backgroundColor:'green', justifyContent:'center', alignItems:'center'}} onClick={()=>{this.loadMore()}}>Load more</View>:null
}
</View>
);
}
}
Set data in state (already done ==> this.state.listData)
Set counter in state (initialize with 1)
Set 15 first elements in state (you can name it "renderedData" or something like that) and then increase cuonter to 1
Add a function that increases the "renderedData" by 15 items by increasing the counter by one
Add Footer component to the list which will call the function you created in stage 3
To take only 15( or 30/45/60 etc..) items from the list you can do something like this:
this.setState({ renderedItem: listData.slice(0, counter*15) })

Is it Possible to navigate from createStackNavigator to createDrawerNavigator?

How is this implemented
I have a stack navigator which i use for Splashscreen and Login, this works fine , now i have a drawerNavigator which is the main home of the Application, Now my worry is, Is this possible , navigating from a stack navigator (username and password) and landing at a homepage (DrawerNavigator) (home page with left side menu)
My code is looking something like this, its a very long code I know, but pls at the same time, I just started out react-native some few days ago. Does anyone think its advisable to use createStackNavigator as well as createDrawerNavigator at the same time?
import React , {Component} from 'react';
import { Platform, View, Text, Image , StyleSheet , ActivityIndicator, Dimensions, Modal, TextInput, TouchableOpacity, Alert } from 'react-native';
import { createAppContainer } from 'react-navigation';
import { createDrawerNavigator } from 'react-navigation-drawer';
import { Header } from 'react-native-elements';
import { Left, Right, Icon } from 'native-base';
import { createStackNavigator } from 'react-navigation-stack';
class SplashScreen extends React.Component{
componentDidMount()
{
setTimeout(() => {
this.props.navigation.navigate('Login')
}, 4000);
}
render(){
return(
<View style={styles.Logocontainer}>
<Image
source={{uri: 'LOGO IMAGE HERE'}}
style={styles.logo} />
<ActivityIndicator size="large" color="blue" style={{margin:10}}/>
</View>
);
}
}
class Login extends React.Component{
login(){
const {username, password} = this.state;
Alert.alert('Login Successful');
this.props.navigation.navigate('Home');
}
render(){
return(
<View style={styles.Logocontainer}>
<Image
source={{uri: 'LOGO IMAGE HERE'}}
style={styles.logo} />
<Text style={{textAlign:'left',fontSize:25,color: '#009999'}}> Sign In {"\n"}</Text>
<TextInput
onChangeText={(username) => this.setState({ username })}
placeholder = "Username"
style={styles.input}
/>
<TextInput
onChangeText={(password) => this.setState({ password })}
placeholder = "Password"
style={styles.input}
secureTextEntry={true} />
<TouchableOpacity style={styles.button} onPress={this.login.bind(this)}>
<Text style={styles.loginbtn}> Login </Text>
</TouchableOpacity>
</View>
);
}
}
class Home extends React.Component{
static navigationOptions = {
drawerLabel: 'Home',
drawerIcon: ({ tintColor }) => (
<Image
source={{uri:'http://imageholder.freeasphost.net/home.png'}}
style={[styles.icon, { tintColor: tintColor }]}
/>
),
};
render()
{
return(
<View style={styles.container}>
<Header
leftComponent={<Icon name="menu" onPress={() => this.props.navigation.openDrawer()} />}
/>
<View style={styles.text}>
<Text> Welcome to Home screen</Text>
</View>
</View>
);
}
}
class Profile extends React.Component{
static navigationOptions = {
drawerLabel: 'Profile',
drawerIcon: ({ tintColor }) => (
<Image
source={{uri:'http://imageholder.freeasphost.net/profile.png'}}
style={[styles.icon, { tintColor: tintColor }]}
/>
),
};
render()
{
return(
<View style={styles.container}>
<Header
leftComponent={<Icon name="menu" onPress={() => this.props.navigation.openDrawer()} />}
/>
<View style={styles.text}>
<Text>Welcome to Profile screen</Text>
</View>
</View>
);
}
}
class Settings extends React.Component{
static navigationOptions = {
drawerLabel: 'Settings',
drawerIcon: ({ tintColor }) => (
<Image
source={{uri:'http://imageholder.freeasphost.net/settings.png'}}
style={[styles.icon, { tintColor: tintColor }]}
/>
),
};
render()
{
return(
<View style={styles.container}>
<Header
leftComponent={<Icon name="menu" onPress={() => this.props.navigation.openDrawer()} />}
/>
<View style={styles.text}>
<Text>Welcome to Settings Screen</Text>
</View>
</View>
);
}
}
const myStackNavigator = createStackNavigator({
SplashScreen:{
screen:SplashScreen
},
Login:{
screen:Login
},
});
const MyDrawerNavigator = createDrawerNavigator({
Home:{
screen:Home
},
Settings:{
screen:Settings
},
Profile:{
screen:Profile
},
});
const MyApp = createAppContainer(MyDrawerNavigator);
const MyPrologue = createAppContainer(myStackNavigator);
export default class App extends Component {
render() {
return (
<MyPrologue/>
);
}
}
const styles = StyleSheet.create({
icon: {
width: 24,
height: 24,
},
container: {
flex: 1
},
text:{
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
Logocontainer:{
flex: 1,
justifyContent :"center",
alignItems:"center"
},
logo:{
width:150,
height:150
},
button:{
width:300,
padding:10,
backgroundColor:'#009999',
alignItems: 'center'
},
input: {
width: 300,
height: 44,
padding: 10,
borderWidth: 1,
borderColor: '#009999',
marginBottom: 10,
},
loginbtn:{
color:'#ffff'
},
});
For this cases i would suggest to use a SwitchNavigator, that renders pretty much like a web application. When you are passing from one screen the previous screen gets unmounted. Only the focused screen will be mounted.
I'll keep your current StackNavigator if you wanted to use it for the header:
First of all you need to import the SwitchNavigator:
import { createSwitchNavigator } from 'react-navigation';
Remove const MyApp = createAppContainer(MyDrawerNavigator); and change
const MyPrologue = createAppContainer(myStackNavigator);
to
const MyPrologue = createAppContainer(switchNavigator );
where switchNavigator is :
const switchNavigator = createSwitchNavigator({
Authentication: {
screen:myStackNavigator
},
DrawerNavigator: {
screen: MyDrawerNavigator
},
},
{
initialRouteName: "Authentication"
})
Then your login function can navigate doing :
this.props.navigation.navigate("DrawerNavigator")
You can read about SwitchNavigator at : https://reactnavigation.org/docs/en/switch-navigator.html#docsNav

React navigation hide one tab

I'm using react-navigation for navigating between screens. Is it possible to have createBottomTabNavigator with 3 tabs, but when you show tab bar, I want to have visible only 2 tabs instead of 3. ?
I made a npm package for this, please see;
https://www.npmjs.com/package/react-navigation-selective-tab-bar
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* #format
* #flow
*/
import React, { Component } from "react";
import { Platform, StyleSheet, Text, View, Button } from "react-native";
import { createBottomTabNavigator, createAppContainer } from "react-navigation";
import BottomTabBar from "react-navigation-selective-tab-bar";
class ScreenOne extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Screen One</Text>
<Text style={styles.number}>1</Text>
<Text style={styles.instructions}>
I AM on the bottom tab Navigator
</Text>
<View style={styles.buttons}>
<Button
title="One"
onPress={() => this.props.navigation.navigate("One")}
/>
<Button
title="Two"
onPress={() => this.props.navigation.navigate("Two")}
/>
<Button
title="Three"
onPress={() => this.props.navigation.navigate("Three")}
/>
<Button
title="Four"
onPress={() => this.props.navigation.navigate("Four")}
/>
</View>
</View>
);
}
}
class ScreenTwo extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Screen Two</Text>
<Text style={styles.number}>2</Text>
<Text style={styles.instructions}>
I am NOT on the bottom tab Navigator
</Text>
<View style={styles.buttons}>
<Button
title="One"
onPress={() => this.props.navigation.navigate("One")}
/>
<Button
title="Two"
onPress={() => this.props.navigation.navigate("Two")}
/>
<Button
title="Three"
onPress={() => this.props.navigation.navigate("Three")}
/>
<Button
title="Four"
onPress={() => this.props.navigation.navigate("Four")}
/>
</View>
</View>
);
}
}
class ScreenThree extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Screen Three</Text>
<Text style={styles.number}>3</Text>
<Text style={styles.instructions}>
I AM on the bottom tab Navigator
</Text>
<View style={styles.buttons}>
<Button
title="One"
onPress={() => this.props.navigation.navigate("One")}
/>
<Button
title="Two"
onPress={() => this.props.navigation.navigate("Two")}
/>
<Button
title="Three"
onPress={() => this.props.navigation.navigate("Three")}
/>
<Button
title="Four"
onPress={() => this.props.navigation.navigate("Four")}
/>
</View>
</View>
);
}
}
class ScreenFour extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>Screen Four</Text>
<Text style={styles.number}>4</Text>
<Text style={styles.instructions}>
I am NOT on the bottom tab Navigator
</Text>
<View style={styles.buttons}>
<Button
title="One"
onPress={() => this.props.navigation.navigate("One")}
/>
<Button
title="Two"
onPress={() => this.props.navigation.navigate("Two")}
/>
<Button
title="Three"
onPress={() => this.props.navigation.navigate("Three")}
/>
<Button
title="Four"
onPress={() => this.props.navigation.navigate("Four")}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#F5FCFF"
},
welcome: {
fontSize: 20,
textAlign: "center",
margin: 10
},
instructions: {
textAlign: "center",
color: "#333333",
marginBottom: 5
},
number: {
fontSize: 50
},
buttons: {
flexDirection: "row"
}
});
const AppNavigator = createBottomTabNavigator(
{
One: {
screen: ScreenOne
},
Two: {
screen: ScreenTwo
},
Three: {
screen: ScreenThree
},
Four: {
screen: ScreenFour
}
},
{
tabBarComponent: props => {
return (
<BottomTabBar
{...props} // Required
display={["One", "Three"]} // Required
background="black" // Optional
/>
);
}
}
);
export default createAppContainer(AppNavigator);
https://github.com/react-navigation/react-navigation/issues/5230#issuecomment-649206507
Here is how you can tell the tab navigator to not render certain routes.
<Tab.Navigator
screenOptions={({ route }) => ({
tabBarButton: [
"Route1ToExclude",
"Route2ToExclude"
].includes(route.name)
? () => {
return null;
}
: undefined,
})}
>
This worked for me, you are still able to navigate to the tab! I changed it to this:
Without a variable:
tabBarButton: ["About"].includes(route.name) ? () => null : undefined
With a variable to hide specific tabs:
const hiddenTabs = ["About", "Food"];
tabBarButton: hiddenTabs.includes(route.name) ? () => null : undefined
With a variable to show specific tabs only:
const tabsToShow = ["About", "Food"];
tabBarButton: !tabsToShow.includes(route.name) ? () => null : undefined
All credit goes to Ben Awad!
Put your third item/screen in a stack navigator:
const Bottom = createBottomTabNavigator({
item1: {screen: Screen1},
item2: {screen: Screen2},
},{
initialRouteName: "item1",
}
)
export default createStackNavigator({
tabs: Bottom,
item3: Screen3,
})
At last, to change the screen to your third route in your component, you can do this:
// ...
import {withNavigation} from 'react-navigation' // IMPORTANT
export default class Example extends React.Component{
render(){
return(
<TouchableOpacity onPress={() => this.props.navigation.navigate('item3')}>
)
}
}
export default withNavigation(Example) // IMPORTANT
For example, if you want to have 5 active routes in a createBottomTabNavigator, but only 3 or another number to show icons in the TabBar. In this case, all 5 routes will be active, and you can go to them props.navigation.navigate()
You must pass a filtered list of routes to the TabBar component, but the object must be sure to be deeply copied (using lodash for example)
import cloneDeep from 'lodash/cloneDeep';
....
const TabBarComponent = props => {
const routeNamesToHide = [
'MyOfficeStack',
'ArenaStack',
'SavedSearchesStack',
'NotificationsStack',
];
// Delete from TABBAR items in array 'routeNamesToHide'
let newNavigation = cloneDeep(props.navigation);
newNavigation.state.routes = newNavigation.state.routes.filter(
item => !routeNamesToHide.includes(item.routeName)
);
//
return <BottomTabBar {...props} navigation={{ ...newNavigation }} />;
};
const tabNavigator = createBottomTabNavigator(
{
SearchStack,
FavouritesStack,
AddScreenStack,
MessagesStack,
BookingsStack,
MyOfficeStack,
AreaStack,
SavedSearchesStack,
NotificationsStack,
},
{
lazy: false,
tabBarOptions: {
showLabel: true,
},
tabBarComponent: props => (
<TabBarComponent {...props} />
),
}
);
the easiest solution is this
<Tab.Screen
name='someroute'
component={SomeComponent}
options={{
tabBarButton: props => null,
}}
/>
this is by far the best solution because it doesn't require extra effort
Ben Awad solution(mentioned by Kayden van Rijn) is good, it allows centralized control, but you need extra effort to make sure the type of the route name array is correct
<Tab.Navigator
screenOptions={({ route }) => {
const toExclude: typeof route.name[] = ['routeName']
return {
tabBarButton: toExclude.includes(route.name)
? () => {
return null
}
: undefined,
}
}}
>
credit

How to add icons to tabs in react-native-tab-view

I am working with react-native-tab-view and I can just put text on tabs but I want icons. There are some answers on GitHub but they are unclear. If you know anything it would be perfect!
1. Get an imported icon library:-
import Icon from 'react-native-vector-icons/AwesomeFont'
2. Create a method for rendering the icons depending on route using props:-
const getTabBarIcon = (props) => {
const {route} = props
if (route.key === 'Search') {
return <Icon name='search' size={30} color={'red'}/>
} else {
return <Icon name='circle' size={30} color={'red'}/>
}
}
3. Render TabView with a rendered TabBar prop calling back to getTabBarIcon:-
export default class App extends React.Component {
state = {
index: 0,
routes: [
{key: 'Home', title: 'Hello'},
{key: 'Search', title: 'Second'}
],
}
render() {
return (
<TabView
navigationState={this.state}
renderScene={SceneMap({
Home: FirstRoute,
Search: SearchScreen,
})}
onIndexChange={index => this.setState({index})}
initialLayout={{height: 100, width: Dimensions.get('window').width}}
renderTabBar={props =>
<TabBar
{...props}
indicatorStyle={{backgroundColor: 'red'}}
renderIcon={
props => getTabBarIcon(props)
}
tabStyle={styles.bubble}
labelStyle={styles.noLabel}
/>
}
tabBarPosition={'bottom'}
/>
);
}
}
4. You can style the TabBar with anything (here the label is hidden to use icon only tabs)
const styles = StyleSheet.create({
scene: {
flex: 1,
},
noLabel: {
display: 'none',
height: 0
},
bubble: {
backgroundColor: 'lime',
paddingHorizontal: 18,
paddingVertical: 12,
borderRadius: 10
},
})
react-native
You have to override renderHeader method and define in TabBar your own render label method:
renderHeader = (props) => (
<TabBar
style={styles.tabBar}
{...props}
renderLabel={({ route, focused }) => (
<View style={styles.tabBarTitleContainer}>
/* HERE ADD IMAGE / ICON */
</View>
)}
renderIndicator={this.renderIndicator}
/>
);
I had the same problem. I solved it as follows by creating a "_renderTabBar" function and passing as props to the renderTabBar method of the TabView component and in this function I put the component "image" as my icon, I hope it helps.
A print:
_renderTabBar = props => {
const inputRange = props.navigationState.routes.map((x, i) => i);
return (
<View style={styles.tabBar}>
{props.navigationState.routes.map((route, i) => {
const color = props.position.interpolate({
inputRange,
outputRange: inputRange.map(
inputIndex => (inputIndex === i ? 'red' : 'cyan')
),
});
return (
<TouchableOpacity
style={[styles.tabItem, {backgroundColor: '#FFF' }]}
onPress={() => this.setState({ index: i })}>
<Image
style={styles.iconTab}
source={{uri: 'https://www.gstatic.com/images/branding/product/2x/google_plus_48dp.png'}}
/>
<Animated.Text style={{ color }}>{route.title}</Animated.Text>
</TouchableOpacity>
);
})}
</View>
);
};
Here you render
render() {
return (
<TabView
navigationState={this.state}
renderScene={this._renderScene}
renderTabBar={this._renderTabBar}
onIndexChange={index => this.setState({ index })}
/>
);
Code complete: https://snack.expo.io/#brunoaraujo/react-native-tab-view-custom-tabbar

Tabbed navigation between screens in react native

I use a StackNavigator based on the react-native-elements example and I want to enable something similar to a link with an ID as a parameter. I want to link to this screen:
const FontsTab = StackNavigator({
Home: {
screen: FontsTabView,
path: '/',
navigationOptions: ({ navigation }) => ({
title: 'Fonts',
headerLeft: (
<Icon
name="menu"
size={30}
type="entypo"
style={{ paddingLeft: 10 }}
onPress={() => navigation.navigate('DrawerOpen')}
/>
),
}),
},
Detail: {
screen: FontsDetailTabView,
path: 'fonts_detail',
navigationOptions: {
title: 'Fonts Detail',
},
},
});
I have this screen where I want the click of the text of an item to open the FontsTabView with the ID as a parameter. I would like to achieve something like the following:
<Text onPress={ (navigation)=> navigation.navigate('FontsTabView ', { id: {item.id} }) } style={styles.listHeader} >{item.title}</Text>
How can it be done?
class Icons extends Component {
constructor() {
super();
const ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2,
});
this.state = {
selectedIndex: 0,
value: 0.5,
dataSource: ds.cloneWithRows(list1),
isLoading: true
};
this.updateIndex = this.updateIndex.bind(this);
this.renderRow = this.renderRow.bind(this);
}
updateIndex(selectedIndex) {
this.setState({ selectedIndex });
}
renderRow(rowData, sectionID) {
return (
<ListItem
key={sectionID}
onPress={log}
title={rowData.title}
icon={{ name: rowData.icon }}
/>
);
}
_renderList = ({ item, navigation }) => {
return (
<TouchableWithoutFeedback onPress={(event) => this._selectedItem(item.key)}>
<View style={styles.listRowContainer}>
<View style={styles.listinside1Container}>
<Image style={styles.listImage} source={item.icon} />
<View style={styles.listContainer} onPress={(event) => this._selectedItem(item.text)} >
<Text onPress={ (navigation)=> navigation.navigate('DrawerOpen') } style={styles.listHeader} >{item.title}</Text>
<Text style={styles.listValue} >{item.value}</Text>
<Image
style={{width: 50, height: 50}}
source={{uri: item.img}}
/>
</View>
</View>
</View>
</TouchableWithoutFeedback>
);
}
componentDidMount(){
return fetch('https://www.koolbusiness.com/in.json')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson.movies,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
render() {
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
const { navigation } = this.props;
const buttons = ['Button1', 'Button2'];
const { selectedIndex } = this.state;
if(this.state.isLoading){
return(
<View style={{flex: 1, padding: 20}}>
<ActivityIndicator/>
</View>
)
}
return (
<ScrollView>
<View style={styles.headerContainer}>
<Icon color="white" name="invert-colors" size={62} />
<Text style={styles.heading}>Trending Ads India</Text>
</View>
<View style={styles.MainContainer}>
</View>
<View style={styles.mainWrapper} >
<FlatList data={this.state.dataSource} renderItem={this._renderList} keyExtractor={(item, index) => index.toString()} />
</View>
</ScrollView>
);
}
}
You were close but not quite there,
Try to render your item like below;
<Text onPress={ ()=> this.props.navigation.navigate('FontsTabView', { id: item.id }) } style={styles.listHeader} >
{item.title}
</Text>
Then in FontsTabView you can read the parameter like below and render your screen accordingly.
this.props.navigation.state.params.id