Adding tab component in a view - react-native

I am new to react native, and I am struggling to understand it. This may be a very basic question.
I have a screen and it consists of a searchbar on top of the page and below it there are Tabs. While navigating through the tabs, the searchbar should not be removed (being at the top level).
MainScreen:
export default class MainScreen extends Component {
render() {
return (
<View>
<Text>My search bar here</Text>
<TabBar></TabBar>
</View>
);
}
}
TabBar:
const routeConfiguration = {
TabEvents: { screen: TabEvents },
TabPeople: { screen: TabPeople },
TabGroups: { screen: TabGroups },
TabMap: { screen: TabMap },
}
const tabBarConfiguration = {
tabBarOptions:{
// some options
}
}
export const TabBar = TabNavigator(routeConfiguration,tabBarConfiguration)
When running the app, only the text is being displayed My search bar here without the tabs.

To be able to show tabs, the navigator acts like a container with "two views". One is for the screens that you wanna show and, at the bottom, the tabs container.
So, for the MainScreen you just only need to define the tabs/screens that want react navigator to render.
In each screen you will put the header as shown above. You could also define a default header in the navigator props.
MainScreen.js:
const MainScreen = TabNavigator({
TabEvents: { screen: TabEvents },
Second: { screen: SecondPage },
Third: { screen: ThirdPage },
Fourth: { screen: FourthPage },
Fifth: { screen: FifthPage }
}
})
export default MainScreen;
MainScreen.js: (with default header)
const MainScreen = TabNavigator({
TabEvents: { screen: TabEvents },
Second: { screen: SecondPage },
Third: { screen: ThirdPage },
Fourth: { screen: FourthPage },
Fifth: { screen: FifthPage }
}, {
navigationOptions: {
header: <YourHeader />
}
})
export default MainScreen;
TabEvents.js
export default class TabEvents extends Component {
render() {
return (
<View>
<YourHeader />
<MoreStuff/>
</View>
);
}
}
You wil have a more detailed example in the docs ( https://github.com/react-community/react-navigation/blob/master/examples/NavigationPlayground/js/SimpleTabs.js & https://reactnavigation.org/docs/navigators/tab)

You can wrap your TabNavigator with StackNavigator.
MyTabNavigator.js
const MyTabNavigator = TabNavigator({
ScreenX: { screen: SceenNameX },
ScreenY: { screen: ScreenNameY }
}, {
initialRouteName: 'ScreenX',
tabBarPosition: 'top',
tabBarOptions: {
activeTintColor: '#af0'
}
})
export default MyTabNavigator
MainScreen.js
export default class MainScreen extends Component {
static navigationOptions = {
header: (props) => (
<SearchBar {...props}/>
)
}
render() {
return (
<MyTabNavigator />
)
}
}
MyStackNavigator.js
const MyStackNavigator = StackNavigator({
Main: { screen: MainScreen }
}, {
initialRouteName: 'Main'
})
export default MyStackNavigator
Now you can call MyStackNavigator to load MainScreen which will render the header SearchBar and the body MyTabNavigator.

The way to create a Tab navigator is the following:
tabNavigator.js
import React from 'react'
import { Platform } from 'react-native'
import { TabNavigator, StackNavigator } from 'react-navigation'
const Tabs = TabNavigator({
Home:{ //this is the name of the screen, by default the first screen that you want to show is called Home
screen: component , //this is the component that you want to show in the screen
navigationOptions: {
tabBarLabel: 'some label', //this will be located as a title for the tab
tabBarIcon: ({ tintColor }) => <i> some icon </i>, //this allow you to show a icon in the tab
//the following options are to customize the header, maybe you don't need this.
title: 'some title',
headerStyle:{
backgroundColor: 'blue' // color for the header
},
headerTitleStyle:{
color: 'white' // color for the text on the header
},
header: <YourHeader/>
}
},
// if you need add some other tab repeat the same pattern here OtherScreen:{ ...}
},{
//this are options to customize the tab itself, I added some good ones.
tabBarOptions: {
activeTintColor: Platform.OS === 'ios' ? primary : white,
style:{
height:40,
backgroundColor: Platform.OS === 'ios' ? white : primary,
shadowRadius: 6,
shadowOpacity: 1,
shadowColor: 'rgba(0,0,0,0.24)',
shadowOffset: {
width: 0,
height: 3
}
}
}
})
export default Tabs
mainScreen.js
import React, { Component} from 'react'
import Tabs from './tabNavigator'
export default class MainScreen extends Component {
render() {
return (
<View>
<Tabs/>
</View>
);
}
}
I hope it helps.

Related

How to style header in react-navigation

I am trying to style the header in react-navigation where the object is automatically generated by Expo.
I am trying to style the header background and the orientation of the title.
I tried every possible place, including navigationOptions but all failed.
In below code tab bar background color is correctly changed. But same method failed for header.
Any guidance appreciated.
import React from 'react';
import { createStackNavigator, createBottomTabNavigator } from 'react-navigation';
import LinksScreen from '../screens/LinksScreen';
import SettingsScreen from '../screens/SettingsScreen';
const LinksStack = createStackNavigator({
Links: LinksScreen,
});
LinksStack.navigationOptions = {
tabBarLabel: "Links",
tabBarIcon: ...
};
const SettingsStack = createStackNavigator({
Settings: SettingsScreen,
});
SettingsStack.navigationOptions = {
tabBarLabel: "Settings",
tabBarIcon: ...,
};
export default createBottomTabNavigator(
{
LinksStack,
SettingsStack,
},
{
tabBarOptions: {
style: {
backgroundColor: '#123456',
},
}
},
);
try this:
static navigationOptions = {
title: 'Chat',
headerStyle: { backgroundColor: 'red' },
headerTitleStyle: { color: 'green' },
}
You can try this
export default createBottomTabNavigator(
{
LinksStack: {
screen: LinksStack,
navigationOptions: LinksStack.navigationOptions(), // style here
},
SettingsStack,
}
You can try this by passing using headerStyle inside each screen by
export default createBottomTabNavigator({
LinkStack: {
screen: LinkScreen,
navigationOptions: { // you need to call LinkStack.navigationOptions here
headerTitle: 'LinkScreen',
headerStyle: {
backgroundColor: 'red',
...otherStyles,
},
},
}
})
Or you can make use of defaultNavigationOptions inside your stackNavigator if you don't have specific header styles for your different screens.
In your case, you need to call LinkStack.navigationOptions for navigationOptions.
Finally I figured out what I was doing wrong.
It seems I was searching the answer in wrong place. The following change solved the problem:
class LinksScreen extends React.Component {
static navigationOptions = {
title: "Links Title",
headerStyle: { backgroundColor: '#123456', },
headerTitleStyle: { color: "#654321" },
};
...
}

Why is 'this.props.navigation' unavailable to screen component?

I have a drawer navigator that has a stack navigator nested inside it as one of the screen options. I have no issues navigating to any screens in the drawer, but when I try to navigate to another screen in the stack navigator, I dont have access to this.props.navigation. Im confused because the screen is declared in my navigator setup.
AppNavigator:
// all imports
const InboxStack = createStackNavigator(
{
Inbox: {
screen: HomeScreen
},
Conversation: {
screen: ConversationScreen
}
},
{
headerMode: "none",
initialRouteName: "Inbox"
}
);
const MainNavigator = createDrawerNavigator(
{
Inbox: InboxStack,
Second: { screen: SecondScreen },
Third: { screen: ThirdScreen }
},
{
drawerPosition: "left",
initialRouteName: "Inbox",
navigationOptions: ({ navigation }) => ({
title: "Drawer Navigator Header",
headerTitleStyle: {
color: "blue"
},
headerLeft: <Text onPress={() => navigation.toggleDrawer()}>Menu</Text>
})
}
);
const WrapperStackNavigator = createStackNavigator({
drawerNav: MainNavigator
});
const AppContainer = createAppContainer(
createSwitchNavigator(
{
AuthLoading: AuthLoadingScreen,
App: WrapperStackNavigator,
Login: LoginScreen,
Register: RegisterScreen
},
{
initialRouteName: "AuthLoading"
}
)
);
export default AppContainer;
utilization of navigation prop in ConversationScreen:
import React from "react";
import { View, Text } from "react-native";
import { connect } from "react-redux";
import { loadConversation } from "../actions";
import MessagesList from "../components/MessagesList.js";
class ConversationScreen extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.loadConversation();
}
loadConversation() {
this.props.loadConversation(
this.props.navigation.state.params.convoId // this works!
this.props.navigation.getParams("convoId") // this does not :(
);
}
render() {
return (
<View
style={{
display: "flex",
alignItems: "center",
justifyContent: "center"
}}
>
<Text>Conversation screen</Text>
<MessagesList messages={this.props.messages} />
</View>
);
}
}
const mapStateToProps = ({ conversation, auth }) => {
const { messages } = conversation;
const { user } = auth;
return { messages, user };
};
const mapDispatchToProps = {
loadConversation
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(ConversationScreen);
The issue exists with ConversationScreen, I dont have access to the navigation prop, but docs say if its declared in the navigator it should be be passed the navigation prop. Every call using this.props.navigation errors with ... is not a function, ... is undefined
... being this.props.navigation.navigate, this.props.navigation.getParams, etc
After checking the props object through alert(this.props) I verified I had access to the navigation object, even though it appeared to be undefined, ultimately using
componentDidMount() {
loadConversation() {
this.props.loadConversation(
this.props.navigation.state.params.convoId
);
}
}
This got me where I needed to be. although it would have been nice to just use this.props.navigation.getParams()

Using Tab and Stack Navigator Together

I am building an App on React-Native for which I am using React-Navigation
Now, Inside that i am using Stack-Navigation and TabNavigator (updated it DrawerNavigator)
import {
createStackNavigator,
TabNavigator,
DrawerNavigator
} from 'react-navigation';
import CoinCapCharts from "./src/container/CoinCapCharts.js"
import CoinCap from './src/container/CoinCap.js';
//THis is being Exported to App.js
export const Tab = TabNavigator({
TabA: {
screen: CoinCap
},
TabB: {
screen: CoinCap
}
}, {
order: ['TabA', 'TabB'],
animationEnabled: true,
})
export const MyScreen = createStackNavigator({
Home: {
screen: CoinCap
},
CoinCapCharts: {
screen: CoinCapCharts
}
},{
initialRouteName: 'Home',
headerMode: 'none'
});
export const Drawer = DrawerNavigator({
Tabs: { screen: Tab },
Stack: { screen: MyScreen },
})
I am importing this in my App.js where I am doing something like this
import React from 'react';
import {
Drawer
}from './Screen.js';
import {
View
} from 'react-native';
export default class App extends React.Component {
render() {
return (
<View>
<Drawer/>
<Tab/>
</View>
);
}
}
Now, This is indeed showing Tab the first time I run my app but after I navigate to different screen and return back, It doesn't appear to be showing that Tab again
[Question:] What could I be doing wrong and How can I fix it?
Try to define one within the other.
Something like:
const Tab = TabNavigator({
TabA: {
screen: Home
},
TabB: {
screen: Home
}
}, {
order: ['TabA', 'TabB'],
animationEnabled: true,
})
export const MyStack = createStackNavigator({
Home: {
screen: Home
},
CoinCapCharts: {
screen: CoinCapCharts
},
Tab: {
screen: Tab
},
},{
initialRouteName: 'Home',
headerMode: 'none'
});
Now, render MyStack (not sure that Screen is the best name :)
export default class App extends React.Component {
render() {
return (
<View>
<MyStack />
</View>
);
}
}

Call child react navigation prop from super component in react-native / react-navigation

I have a react native application using react navigation. I have following structure in my application.
class MainContainer extends Component {
render() {
return (
<View style={{ flex: 1 }}>
<Header
backgroundColor={appcolors.primaryColor}
leftComponent={<TouchableOpacity onPress={() => this.props.navigation.toggleDrawer() }><Feather name='align-justify' size={24} color='white' /></TouchableOpacity>}
centerComponent={{ text: this.props.headerTitle , style: { color: 'white' } }}
/>
<MainDrawerNavigation/>
</View>
);
}
};
and <MainDrawerNavigation/> is a react navigation component as follows.
MainDrawerNavigation = createDrawerNavigator({
XScreen: {
screen: XScreen,
},
YScreen: {
screen: YScreen,
},
ZScreen: {
screen: ZScreen,
},
},{
}
});
I have got error when trying to call this.props.navigation.toggleDrawer() from MainContainer. Then for testing purpose I have add a button to XScreen and tried to toggle drawer and it was success. So I want to know is there any way to pass child navigation props to super view. So I could call this.props.navigation.toggleDrawer() method and control drawer from MainContainer. or any navigation practices that can be use to solve this.
PS: the error I got is _this2.props.navigation.toggleDrawer is not a function
In MainContainer, the this.props.navigation is not initiated, so you got such error. You can only access it inside the child component of MainDrawerNavigation i.e. XScreen, YScreen & ZScreen only.
For best practices you need to design how all component will navigate into your app and pass Navigator objects/components as root component.
There are multiple navigators, you will can read them react navigation api doc.
A simplified app needs SwitchNavigator, DrawerNavigator, TabBarNavigator & StackNavigator.
SwitchNavigator :
It is used for user authentication. It will give control to toggle between two component (FYI, component can be a Navigator or React.Component).
export const AuthNavigator = SwitchNavigator(
{
AuthLoading: { screen: AuthLoadingScreen },
App: { screen: AppDrawer},
Auth: { screen: AuthStack}
},
{
initialRouteName: 'AuthLoading',
}
);
for more details
DrawerNavigator :
It is used to display side panel or sliding view at left or right side of the screen. So, you can directly pass this component to SwitchNavigator's authentication successful screen.
export default const AppDrawer = DrawerNavigator(
{
Home: { screen: TabBarNav },
Notes: { screen: NotesStack },
Invite: { screen: InviteContactsStack },
Files: { screen: FilesStack },
Settings: { screen: SettingsStack }
},
{
initialRouteName: "Home",
contentOptions: {
activeTintColor: "#e91e63"
},
contentComponent: props => <LeftSidePanel {...props} />
}
);
TabBarNavigator :
It is used to display tab bar at bottom for iOS and at top for android by default. This can be customized.
export default const TabBarNav = TabNavigator(
{
ChatsTab: {
screen: ChatsStack,
navigationOptions: {
tabBarLabel: "Chats"
}
},
InviteContacts: {
screen: InviteContactsStack,
navigationOptions: {
tabBarLabel: "Invite"
}
},
Notifications: {
screen: NotificationsStack,
navigationOptions: {
tabBarLabel: "Notifications"
}
},
Tasks: {
screen: TasksStack,
navigationOptions: {
tabBarLabel: "Tasks"
}
}
},
{
tabBarPosition: "bottom",
}
);
StackNavigator :
It's name suggests that it will hold a stack of component. So, when any item is selected from drawer, you can directly put a StackNavigator in that screen.
export default const ChatsStack = StackNavigator({
Chats: {
screen: Chats
},
Messages: {
screen: Messages
}
});
You can read Spencer Carli's blog on medium which explain with code.
Please let me know whether it satisfies your need.

Custom header in nested TabNavigator

I have a fairly complication navigation flow requirement for an app I'm working on.
I have a bottom tab bar, for each tab I'll be having a top tab bar for additional related views.
Which I have working, however on the videos tab in the nested "All" tab, I need to add a search bar to the header, and on the "Favourites" tab I'll be having yet another custom header with an "Edit" button at the top right.
How can I achieve this navigation whilst allowing React Navigation to co-ordinate everything. See images below:
What I don't want to do is disable the header at the MainNavigator level and enable it for particular routes. Or even worse embed the header and the tab bar on individual containers.
routes.js
import {
StackNavigator,
TabNavigator,
DrawerNavigator
} from "react-navigation";
import Feed from "./containers/Feed";
import Auth from "./containers/Auth";
import News from "./containers/News";
import Videos from "./containers/Videos";
import FavouriteVideos from "./containers/FavouriteVideos";
const DashboardNavigator = TabNavigator(
{
Feed: {
screen: Feed
},
News: {
screen: News
}
},
{
tabBarPosition: "top"
}
);
const VideoNavigator = TabNavigator(
{
Videos: {
screen: Videos,
navigationOptions: {
title: "All"
}
},
Favourites: {
screen: FavouriteVideos
}
},
{
tabBarPosition: "top"
}
);
const MainNavigator = TabNavigator(
{
Dashboard: {
screen: DashboardNavigator,
navigationOptions: ({}) => ({
title: "Dashboard"
})
},
Video: {
screen: VideoNavigator,
navigationOptions: ({}) => ({
title: "Videos"
})
}
},
{
swipeEnabled: false,
animationEnabled: false,
tabBarPosition: "bottom"
}
);
const AuthenticatedNavigator = DrawerNavigator({
App: {
screen: MainNavigator
}
});
const RootNavigator = StackNavigator({
LoggedOut: {
screen: Auth
},
Authenticated: {
screen: AuthenticatedNavigator
}
});
export default RootNavigator;
Snack
https://snack.expo.io/H1qeJrLiM
Images
You can use react-navigation addListener function with combination setParams to achieve desired behavior.
You can listen for focus and blur events and then change a parameter. Then in your route config you can look for this parameter and decide what to render for header. I changed your snack to show a working example of what I am suggesting.
Example
const MainNavigator = TabNavigator(
{
Dashboard: {
screen: DashboardNavigator,
navigationOptions: ({}) => ({
title: "Dashboard"
})
},
Video: {
screen: VideoNavigator,
navigationOptions: ({navigation}) => {
let title = 'Videos';
navigation.state.routes.forEach((route) => {
if(route.routeName === 'Videos' && route.params) {
title = route.params.title;
}
});
// I set title here but you can set a custom Header component
return {
tabBarLabel: 'Video',
title
}
}
}
},
{
swipeEnabled: false,
animationEnabled: false,
tabBarPosition: "bottom"
}
);
export default class Videos extends Component {
constructor(props) {
super(props);
this.willFocusSubscription = props.navigation.addListener(
'willFocus',
payload => {
this.props.navigation.setParams({title: 'All Videos'});
}
);
this.willBlurSubscription = props.navigation.addListener(
'willBlur',
payload => {
this.props.navigation.setParams({title: 'Just Videos'});
}
);
}
componentWillUnmount() {
this.willFocusSubscription.remove();
this.willBlurSubscription.remove();
}
render() {
return (
<View>
<Text> Videos </Text>
</View>
);
}
}