React Native Breadcrumb - reactjs

I am making a React Native application in which I have menus and submenus.
Menus and submenus structure:
let arr = [
{
name: 'Header 1',
routeName: 'Home',
child: [
{ name: 'Header 1 - Submenu 1', child: [], routeName: 'Home' },
{
name: 'Header 1 - Submenu 2',
child: [],
routeName: 'NotificationScreen',
},
{ name: 'Header 1 - Submenu 3', child: [], routeName: 'Home' },
],
},
{
name: 'Header 2',
routeName: 'NotificationScreen',
child: [
{
name: 'Header 2 - Submenu 1',
child: [],
routeName: 'NotificationScreen',
},
{ name: 'Header 2 - Submenu 2', child: [], routeName: 'Home' },
{
name: 'Header 2 - Submenu 3',
child: [],
routeName: 'NotificationScreen',
},
],
},
];
Render of Menu's and Submenu's:
<TouchableOpacity style={styles.item} onPress={onPress} activeOpacity={1}>
<View style={styles.row}>
<Text style={{ paddingRight: 20 }}>{name}</Text>
{child.length ? <Text>{open ? 'close' : 'open'}</Text> : null}
</View>
{open &&
child.map((x: any, i: any) => {
if (x.child.length) {
return (
<Item
key={x}
active={childActive}
i={i}
setActive={setChildActive}
child={x.child}
/>
);
}
return (
<TouchableOpacity
key={x}
style={styles.subItem}
onPress={() => {
handleRouteChange(x.routeName);
}}>
<Text>
{name} - submenu - {i + 1}
</Text>
</TouchableOpacity>
);
})}
</TouchableOpacity>
Working example: https://snack.expo.dev/#manirajmurugan/custom-header-title-component
Here I am in the need to make a breadcrumb like structure on the screen page as per the navigation done by user through menu and submenus.
Current Scenario:
-> If user clicks on Header 1 and then select submenu Header 1 - Submenu 1, then the user will be redirected to Home Screen.
Expected Scenario:
-> Requirement here is that I am in the need to display a breadcrumb for this screen like,
Header 1 > Header 1 - Submenu 1
On click of the Header 1 in this breadcrumb, user will be redirected to the respective routeName given in the object.
Kindly help me to generate breadcrumb for the navigation done in menu for the respective screen's.
Thanks in advance.
Edit:
In real app menu and submenu will be like,
Here if user click's on Stored Data configuration under Unit Data Management,
then the expected breadcrumb result would be,

Create a piece of state to hold the crumbs. It will be an array that will hold three values: the screen you are currently on, the section title press, and the section item pressed. Handling the last two will be done by the SectionList and to keep track of the current screen you can add a screenListener to the StackNavigator that will listen for all navigation changes on all screens.
import React, { useState, createContext } from 'react';
import { View, StyleSheet, useWindowDimensions } from 'react-native';
import { NavigationContainer } from '#react-navigation/native';
import { createNativeStackNavigator } from '#react-navigation/native-stack';
import Header from './screens/Header';
import HomeScreen from './screens/Home';
import SettingsScreen from './screens/Settings';
const Stack = createNativeStackNavigator();
import { ICON_SIZE, headerHeight } from './Constants';
const initialScreen = 'Settings';
export default function App() {
// this will have at most 3 items:
// the current screen
// the section header
// the section.data[index]
const [crumbNavigation, setCrumbNavigation] = useState([initialScreen]);
const { width, height } = useWindowDimensions();
const screenOptions = {
// pass crumbNavigation and its setter to header
headerTitle: (props) => (
<Header
{...props}
width={width}
height={headerHeight}
crumbNavigation={crumbNavigation}
setCrumbNavigation={setCrumbNavigation}
/>
),
headerStyle: {
height: headerHeight,
width: width,
},
// since there will be a bread crumb navigator
// theres no need for back button
headerBackVisible: false,
headerLeft: () => null,
};
return (
<NavigationContainer>
<Stack.Navigator
initialRouteName={initialScreen}
screenOptions={screenOptions}
screenListeners={{
state: (nav) => {
console.log(nav.type);
const routes = nav.data.state.routes;
const lastRoute = routes[routes.length - 1]?.name;
if (lastRoute)
setCrumbNavigation((prev) => {
prev[0] = lastRoute;
return prev;
});
},
}}>
<Stack.Screen name="Home" component={HomeScreen} />
<Stack.Screen name="Settings" component={SettingsScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
Now that current screen is handled, you can move on to deal with getting the SectionTitle, which the SectionHeader and MenuItem components handles. If a section data array's length is zero, pressing it will trigger the parent component's onItemPress with the section as an argument, if not, then pressing it will reveal its children
import { useState } from 'react';
import { TouchableOpacity, Text, View, StyleSheet } from 'react-native';
import TouchableMaterialIcon from './TouchableMaterialIcon';
import { ICON_SIZE } from '../Constants';
export default function SectionHeader({ section, toggleSectionMenu, onPress }) {
return (
<TouchableOpacity
style={[
styles.headerContainer,
section.isOpen && styles.highlightedTitleContainer,
]}
onPress={()=>{
if(section.data.length > 0)
toggleSectionMenu(section.id)
else
onPress(section.title)
}}
>
<View style={{ flex: 1 }}>
<Text
styles={[
styles.titleText,
section.isOpen && styles.highlightedTitleText,
]}>
{section.title}
</Text>
</View>
{section.data.length > 0 && (
<TouchableMaterialIcon
name={section.isOpen ? 'keyboard-arrow-up' : 'keyboard-arrow-down'}
size={ICON_SIZE * 0.6}
onPress={() => toggleSectionMenu(section.id)}
/>
)}
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
headerContainer: {
width: '100%',
flexDirection: 'row',
// justifyContent:'center',
alignItems: 'center',
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: '#eee',
paddingVertical: 5,
},
titleText: {
fontSize: 16,
},
highlightedTitleText: {
fontWeight: 'bold',
},
highlightedTitleContainer: {
backgroundColor: '#edf',
},
});
The SectionItem is pretty straightforward. When visible, its a button that when pressed will trigger its grandparent's onItemPressed with both the section title and the item's title
import { View, StyleSheet, Text, TouchableOpacity } from 'react-native';
export default function MenuItem({ section, index, item, onPress }) {
const isLastItem = index == section.data.length - 1;
if (section.isOpen)
return (
<TouchableOpacity
style={[styles.itemContainer, isLastItem && styles.lastItem]}
onPress={() => onPress(section.title, item)}>
<Text>{item}</Text>
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
itemContainer: {
marginRight: 5,
padding: 5,
},
lastItem: {
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: '#eee',
},
});
ButtonWithMenu contains a button that when pressed, renders the SectionList directly beneath it. It accepts an onItemPress prop which will be passed on into the SectionList:
import React, { useState } from 'react';
import {
Text,
View,
StyleSheet,
SectionList,
useWindowDimensions,
Modal,
TouchableWithoutFeedback,
} from 'react-native';
import TouchableMaterialIcon from './TouchableMaterialIcon';
import MenuItem from './MenuItem';
import SectionHeader from './SectionHeader';
import useLayout from '../hooks/useLayout';
export default function DropDownButtonMenu({
name,
size,
color,
onItemPress,
buttonStyle,
containerStyle,
menu,
onMenuAction,
}) {
const [openMenu, setOpenMenu] = useState(false);
const [buttonLayout, onButtonLayout] = useLayout();
// add additional state to menu
const [menuItems, setMenuItems] = useState(
menu?.map((section, i) => {
section.isOpened = false;
section.id = `section-item-${i}`;
return section;
}) || []
);
const { width, height } = useWindowDimensions();
const handleButtonPress = () => {
setOpenMenu((prev) => !prev);
};
const toggleSectionMenu = (sectionId) => {
// deep clone menuItems
const newData = JSON.parse(JSON.stringify(menuItems));
const index = newData.findIndex((section) => section.id == sectionId);
if (index < 0) {
console.log('Section id not found');
return;
}
newData[index].isOpen = !newData[index].isOpen;
setMenuItems(newData);
};
const handleItemPress = (sectionTitle,itemTitle)=>{
onItemPress(sectionTitle,itemTitle)
setOpenMenu(false)
}
return (
<View style={[containerStyle, { zIndex: 1 }]}>
<TouchableMaterialIcon
style={buttonStyle}
name={name}
size={size}
color={color}
onLayout={onButtonLayout}
onPress={handleButtonPress}
disabled={menuItems.length < 1}
/>
{/*
wrap modal in touchable so that pressing outside modal will close it
tried to use absolute positioned view but no matter the zIndex but
the screen contents would always appear on top
*/}
<TouchableWithoutFeedback onPress={() => setOpenMenu(false)}>
<Modal transparent visible={openMenu}>
<View
style={[
styles.menu,
{
top: buttonLayout.y + buttonLayout.height,
left: buttonLayout.left,
minWidth: 150,
maxHeight: height * 0.6,
},
]}>
<SectionList
sections={menuItems}
renderItem={(props) => <MenuItem {...props} onPress={handleItemPress} />}
renderSectionHeader={(props) => (
<SectionHeader
{...props}
toggleSectionMenu={toggleSectionMenu}
onPress={handleItemPress}
/>
)}
/>
</View>
</Modal>
</TouchableWithoutFeedback>
</View>
);
}
const styles = StyleSheet.create({
menu: {
position: 'absolute',
backgroundColor: 'white',
padding: 10,
zIndex: 10,
},
});
Now in the Header component the only thing that is left to do is create a list for the SectionList to render and then update the crumb state with onItemPress:
import { useContext } from 'react';
import { View, StyleSheet, Text, useWindowDimensions } from 'react-native';
import ButtonWithMenu from '../components/ButtonWithMenu';
import { LinearGradient } from 'expo-linear-gradient';
import { ICON_SIZE } from '../Constants';
export default function Header({width,height,crumbNavigation,setCrumbNavigation}) {
return (
<View style={{flex:1,height, width}}>
<View style={styles.navbar}>
<ButtonWithMenu
containerStyle={[styles.navbarButton,{marginLeft:ICON_SIZE}]}
name="home"
size={ICON_SIZE}
color="black"
/>
<ButtonWithMenu
containerStyle={styles.navbarButton}
name="close"
size={ICON_SIZE}
color="black"
onItemPress={(sectionTitle, itemTitle) =>
setCrumbNavigation((prev) => {
const newCrumbNav = [prev[0]];
if (sectionTitle) newCrumbNav.push(sectionTitle);
if (itemTitle) newCrumbNav.push(itemTitle);
return newCrumbNav;
})
}
menu={[
{ title: 'Disconnect from Unit', data: [] },
{ title: 'Monitor Unit', data: ['This Thing', 'That Thing'] },
{ title: 'Unit Settings', data: ['This Thing', 'That Thing'] },
{
title: 'Unit Data Management',
data: ['Stored Data Configuration', 'Stored Data Snapshot'],
},
{ title: 'Information', data: ['This Thing', 'That Thing'] },
{ title: 'Help', data: ['This Thing', 'That Thing'] },
]}
/>
</View>
<LinearGradient
colors={['#902337', '#21458d']}
style={styles.colorBar}
start={{ x: 1, y: 1 }}
locations={[0.5, 0.8]}
/>
<View style={styles.crumbs}>
<Text style={styles.crumbScreen} numberOfLines={1}>
{crumbNavigation[0]} {crumbNavigation.length > 1 && ' > '}
<Text style={styles.crumbTitle}>
{crumbNavigation.slice(1).join(' : ')}
</Text>
</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
navbar: {
flexDirection: 'row',
},
colorBar: {
height: 5,
width: '100%',
},
navbarButton: {
// marginHorizontal: 10,
paddingHorizontal: ICON_SIZE * 0.25,
},
crumbs: {
overflow:'hidden',
flexWrap:'none'
},
crumbScreen: {
fontWeight: 'bold',
},
crumbTitle: {
color: '#21458d',
fontWeight: '400',
},
});
Demo

For readability, I started by moving all of the components into their own separate files. I also used a FlatList instead of a ScrollView for the recursive SubMenuItem rendering.
I first broke the breadcrumb down into three components. The first, MenuItem, which would always be visible in the Header. When pressed, it would reveals a dropdown menu, which would reveal the SubMenu, MenuItem's children. Pressing SubMenu would reveal its children, if it had any, or would trigger navigation, if a routeName was provided. Demo

Related

Adding Placeholder Kind of Functionality into React-Native Picker

I have set up a reusable drop-menu component in my React-native app that uses the native picker. The less than ideal situation I'm running into is that since there is no placeholder property available on picker, if I add 'Select Type' to the list of menu items, that will show up as an option in the menu that opens up. That's obviously not ideal. How can I work a placeholder kind of functionality into this, so that 'Select Type' is initially displayed without showing up in the menu that pops up when the user presses to open the menu?
{
!this.state.otherTypeSelected ?
(
<View style={styles.forms.fieldContainer}>
<Text style={styles.forms.fieldLabel}>Type</Text>
<DropDownMenu
style={styles.forms.pickerContainer}
itemStyle={styles.forms.pickerItem}
items={[
{ label: 'A', value: 'A' },
{ label: 'B', value: 'B' },
{ label: 'C', value: 'C' },
{ label: 'D', value: 'D' },
{ label: 'Other', value: 'Other' }
]}
onSelectMenuValue={this.handleContactTypeSelection}
/>
</View>
) : null
}
And the DropDownMenu code looks like this:
export const DropDownMenu = (props) => {
const [selectedValue, setSelectedValue] = useState(null);
return (
<View style={componentStyles.container}>
<Picker
{...props}
selectedValue={selectedValue}
onValueChange={(itemValue, itemIndex) => {
props.onSelectMenuValue(itemValue),
setSelectedValue(itemValue)
}}
>
{props.items.map(item => <Picker.Item label={item.label} value={item.value} />)}
</Picker>
</View>
);
}
Note, while I could make my first menu item an empty string, with something like { label: '', value: 0 }, the space representing that value will still show up in my drop-menu, which is also not what I'm looking for.
The Picker in react-native has been deprecated. There are only two methods in order to use the Picker
Use any library for Picker.
Create your own Picker (where you will have all the controls with you.)
You can create a simple functional component such as:
Note: This was created in 5 mins, so don't expect this to be pretty :P But it is working
import React, { useState } from "react";
import { Text, View, StyleSheet, TouchableOpacity } from "react-native";
// Dropdown Item component
const DropDownItem = (props) => {
return <TouchableOpacity onPress={() => {
props.onPress(props.label)
props.hideDropdown(false)
}}>
<Text>{props.label}</Text>
</TouchableOpacity>
}
// Custom Picker Component
const CustomPicker = () => {
const [showValue, toggleView] = useState(false)
const [selectedVal, changeValue] = useState('')
return <>
{selectedVal && <TouchableOpacity onPress={() => changeValue('')}>
<Text>Clear Value</Text>
</TouchableOpacity>}
<View style={styles.pickerView}>
<TouchableOpacity style={styles.placeholderView} onPress={() => toggleView(!showValue)}>
<Text style>{selectedVal || "Select a value..."}</Text>
</TouchableOpacity>
{showValue && <View style={styles.dropDownView}>
<DropDownItem label="Value 1" hideDropdown={toggleView} onPress={val => changeValue(val)} />
<DropDownItem label="Value 2" hideDropdown={toggleView} onPress={val => changeValue(val)} />
<DropDownItem label="Value 3" hideDropdown={toggleView} onPress={val => changeValue(val)} />
</View>}
</View>
</>
}
const App = () => {
return (
<View style={styles.container}>
<CustomPicker />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 40,
alignItems: "center"
},
pickerView: {
width: 160,
height: 30,
padding: 3,
},
placeholderView: {
flex: 1,
backgroundColor: '#e0e0e0',
padding: 3
},
dropDownView: {
position: 'absolute',
top: 32
}
});
export default App;
Link: https://snack.expo.io/MBb60jEQw
Happy Coding !!!

React Native: Why does FlatList re-render completely on data changes?

thanks for reading my question! I am struggling with this problem since a few days now: My Flatlist component re-renders all items in the list every time I make a change to the underlying data.
Situation:
I have a FlatList component rendering Items which contain a TouchableOpacity object to toggle Favorite status on this item.
If this button is pressed, I expect only this specific item to change/re-render in my FlatList instead of all items. It feels like as soon as I update state by calling setListData, it re-renders everything.
I have encountered this issue in a more complex setup but was able to drill it down to this core problem. Or is this actually the expected behavior?
Code:
import React, { useState } from "react";
import {
View,
Text,
StyleSheet,
FlatList,
TouchableOpacity,
} from "react-native";
const PlanerScreen = () => {
const [listData, setListData] = useState([
{ id: "1", name: "Banana", isFav: true },
{ id: "2", name: "Apple", isFav: false },
]);
const Item = ({ item, onPressHandler }) => {
console.log(item.name, " rendered");
const color = item.isFav ? "red" : "green";
return (
<View
style={{
flexDirection: "row",
width: "100%",
margin: 10,
}}
>
<Text>{item.name}</Text>
<TouchableOpacity
style={{ width: 100, height: 50, backgroundColor: color }}
onPress={onPressHandler}
/>
</View>
);
};
const favHandler = (id) => {
setListData(
listData.map((item) =>
item.id === id ? { ...item, isFav: !item.isFav } : item
)
);
};
console.log("FlatList rendered");
return (
<View style={{ flex: 1 }}>
<StatusBar style={selectedTheme === "light" ? "dark" : "light"} />
<FlatList
data={listData}
renderItem={({ item }) => (
<Item item={item} onPressHandler={() => favHandler(item.id)} />
)}
keyExtractor={(item) => item.id}
/>
</View>
);
};
export default PlanerScreen;
Console Output on clicking the Favorite Toggle Button:
FlatList rendered
Banana rendered
Apple rendered
FlatList rendered
Banana rendered
Apple rendered
FlatList rendered
Banana rendered
Apple rendered
You can use React.memo which is an alternative to shouldComponentUpdate for functional components.
It tells React when to re-render the component based on prev and next props.
import React, { useState, useCallback } from "react";
import {
View,
Text,
StyleSheet,
FlatList,
TouchableOpacity,
} from "react-native";
const styles = StyleSheet.create({
container: {
flex: 1,
}
})
const keyExtractor = (item) => item.id;
const Item = React.memo(({ item, onPressHandler }) => {
console.log(item.name, " rendered");
const color = item.isFav ? "red" : "green";
return (
<View
style={{
flexDirection: "row",
width: "100%",
margin: 10,
}}
>
<Text>{item.name}</Text>
<TouchableOpacity
style={{ width: 100, height: 50, backgroundColor: color }}
onPress={() => onPressHandler(item.id)}
/>
</View>
);
}, (prevProps, nextProps) => {
if (prevProps.item.isFav === nextProps.item.isFav) return true;
return false;
});
const PlanerScreen = () => {
const [listData, setListData] = useState([
{ id: "1", name: "Banana", isFav: true },
{ id: "2", name: "Apple", isFav: false },
]);
const favHandler = useCallback((id) => {
setListData(prevState => {
return prevState.map((item) =>
item.id === id ? { ...item, isFav: !item.isFav } : item
)
}
);
}, []);
console.log("### FlatList rendered #####");
return (
<View style={styles.container}>
<FlatList
data={listData}
renderItem={({ item }) => <Item item={item} onPressHandler={favHandler} />}
keyExtractor={keyExtractor}
/>
</View>
);
};
export default PlanerScreen;

React native how to animate view opening up->down

Consider the following component where the user selects an option from a list:
import React, { Component } from "react";
import PropTypes from "prop-types";
import {
View,
Text,
StyleSheet,
Platform,
FlatList,
TouchableNativeFeedback,
TouchableOpacity,
PLatform
} from "react-native";
import Icon from "react-native-vector-icons/Ionicons";
import { colors, metrics } from "../../themes";
const Touchable =
Platform.OS === "android" ? TouchableNativeFeedback : TouchableOpacity;
class MenuSelector extends Component<{
onSelect: () => any,
config: object,
selected: string
}> {
state = {
listOpened: false
};
handlePress = id => {
this.props.onPress(id);
};
handleSelect = id => {
if (this.props.onSelect) this.props.onSelect(id);
this.setState({
listOpened: false
});
};
handleMenu = () => {
this.setState({
listOpened: !this.state.listOpened
});
};
render = () => {
let title = "";
if (this.props.config) {
title = this.props.config[0].title;
if (this.props.selected) {
let found = this.props.config.find(item => {
return item.id === this.props.selected;
});
if (found) title = found.title;
}
}
let top = (
<View style={styles.header}>
<Text style={styles.text}>{title}</Text>
<Touchable>
<Text style={styles.text}>
<Icon
name={"ios-menu"}
size={20}
onPress={this.handleMenu}
/>
</Text>
</Touchable>
</View>
);
let list = null;
if (this.state.listOpened === true) {
list = (
<FlatList
data={this.props.config}
renderItem={({ item }) => (
<Touchable onPress={this.handleSelect}>
<Text style={[styles.text, styles.listItem]}>{item.title}</Text>
</Touchable>
)}
/>
);
}
return (
<View style={styles.container}>
{top}
{list}
</View>
);
};
}
export default MenuSelector;
const styles = StyleSheet.create({
container: {
flex: -1,
flexDirection: "column"
},
header: {
flex: -1,
flexDirection: "row",
justifyContent: "space-between",
padding: 10,
backgroundColor: "blue"
},
text: {
fontSize: 16,
color: "white",
textAlign: "center",
fontWeight: "bold"
},
listItem: {
padding: 10,
backgroundColor: "blue"
}
});
The component is used in the following context:
let config = [
{
title="Option 1",
id="option1"
},
{
title="Option 2",
id="option2"
},
{
title="Option 3",
id="option3"
},
{
title="Option 4",
id="option4"
},
];
return (
<View style={styles.container}>
<MenuSelector
config={config.options}
selected={this.state.mode}
onPress={this.handleButtonListPress}
/>
<FlatList
data={this.props.data}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item }) => (
<Text style={styles.text}>{item.name}</Text>
)}
/>
</View>
);
As it is, the <MenuSelector> component appears "at once" on screen. I need to add an sliding effect to <MenuSelector>, "pushing down" the data FlatList when appearing on screen...
On closing, same behaviour, but animating from down to up.
How can I add such animation behaviour to my MenuSelector component ?

React Native Navigation with React Native Admob About

I created a 3 page application with React native navigation. Admob ads are on the 3rd page. I want to try the same ad code on all three screens. If there is any idea in this matter, please share. Thank you.
For better understanding I give the following expo code.
import React, { Component } from 'react';
import {
WebView,
AppRegistry,
StyleSheet,
Text,
View,
Button,
Alert
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import ListComponent from './ListComponent';
class App extends Component {
static navigationOptions = {
title: 'App',
};
OpenSecondActivityFunction = () => {
this.props.navigation.navigate('Second');
};
render() {
return (
<View style={styles.container}>
<Button
onPress={this.OpenSecondActivityFunction}
title="Open Second Activity"
/>
</View>
);
}
}
class SecondActivity extends Component {
static navigationOptions = {
title: 'SecondActivity',
};
OpenThirdActivityFunction = data => {
this.props.navigation.navigate('Third');
};
render() {
return (
<View style={{ flex: 1 }}>
<ListComponent
OpenThirdActivityFunction={this.OpenThirdActivityFunction}
/>
</View>
);
}
}
class ThirdActivity extends Component {
static navigationOptions = {
title: 'ThirdSecondActivity',
};
render() {
return (
<View style={{ flex: 1 }}>
<Text>3</Text>
</View>
);
}
}
const ActivityProject = StackNavigator({
First: { screen: App },
Second: { screen: SecondActivity },
Third: { screen: ThirdActivity },
});
export default ActivityProject;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
}
});
Listcomponent.js
import React, { Component } from 'react';
import {
AppRegistry,
View,
Text,
FlatList,
ActivityIndicator,
} from 'react-native';
import { List, ListItem, SearchBar } from 'react-native-elements';
class ListComponents extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
data: [],
page: 1,
seed: 1,
error: null,
refreshing: false,
};
}
renderSeparator = () => {
return (
<View
style={{
height: 1,
width: '98%',
backgroundColor: '#CED0CE',
marginLeft: '2%',
}}
/>
);
};
renderHeader = () => {
return <SearchBar placeholder="Type Here..." lightTheme round />;
};
renderFooter = () => {
if (!this.state.loading) return null;
return (
<View
style={{
paddingVertical: 20,
borderTopWidth: 1,
borderColor: '#CED0CE',
}}>
<ActivityIndicator animating size="large" />
</View>
);
};
render() {
return (
<List containerStyle={{ borderTopWidth: 0, borderBottomWidth: 0 }}>
<FlatList
data={[{ name: 1, coders: 2 }]}
renderItem={({ item }) => (
<ListItem
roundAvatar
title={`${item.name}`}
subtitle={item.coders}
containerStyle={{ borderBottomWidth: 0 }}
onPress={() => this.props.OpenThirdActivityFunction(item.coders)}
/>
)}
keyExtractor={item => item.coders}
ItemSeparatorComponent={this.renderSeparator}
ListHeaderComponent={this.renderHeader}
ListFooterComponent={this.renderFooter}
/>
</List>
);
}
}
export default ListComponents;

React Navigation failed. No errors

I'm trying to navigate from tab page to other page. I'm following tabnavigator and stacknavigator.
myTabsHost(RegisterHostPage) Here I'm hosting two tabs
import React, { Component } from "react";
import {
AppRegistry,
Text,
View,
Image,
StyleSheet,
TouchableOpacity
} from "react-native";
import { TabNavigator } from "react-navigation";
import { Tab } from "../../config/router.js";
import {Tab2} from "../../config/router.js";
import { NavigationActions } from "react-navigation";
class RegisterHost extends Component {
render() {
return (
<View style={Styles.container}>
<Text style={Styles.boldLabel}> User Register</Text>
<Text style={Styles.normalLabel}>Wallet account registration</Text>
<TouchableOpacity
onPress={() => {
const navigateAction = NavigationActions.navigate({
key: null,
routeName: "preactivate",
params: {}
});
this.props.navigation.dispatch(navigateAction);
}}
>
<Text>topreactivate</Text>
</TouchableOpacity>
<Tab2 />
</View>
);
}
}
const Styles = StyleSheet.create({
container: {
flex: 1,
padding: 2,
justifyContent: "center",
backgroundColor: "#FFFFFF"
},
boldLabel: {
fontWeight: "bold",
fontSize: 24,
alignSelf: "center",
color: "#08AE9E",
marginBottom: 20,
marginTop: 10
},
normalLabel: {
fontWeight: "normal",
fontSize: 18,
alignSelf: "center",
color: "black",
marginBottom: 20,
marginTop: 10
}
});
export default RegisterHost;
myTabPage (BankCustomerRegister)
import React, { Component } from "react";
import {
Text,
View,
Image,
StyleSheet,
TextInput,
TouchableOpacity
} from "react-native";
import { TabNavigator } from "react-navigation";
import{StackNavigator} from 'react-navigation';
import FetchData from "../../utils/fetch.js";
class BankCustomerRegister extends Component {
constructor(props) {
super(props);
this.state = {
stCustId: "",
stIdcard: "",
stPhoneNum: "",
isMounted: false
};
}
}
};
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<Image source={require("../../resources/icons/bank.png")} />
<TextInput
style={styles.textInput}
onChangeText={this._handleCustId}
placeholderTextColor="black"
placeholder="Customer ID"
/>
<TextInput
style={styles.textInput}
placeholderTextColor="black"
onChangeText={this._handleIdCard}
placeholder="ID card"
/>
<TextInput
style={styles.textInput}
placeholderTextColor="black"
onChangeText={this._handlePhoneNum}
placeholder="Phone No"
/>
<TouchableOpacity
onPress={() => {
// NOTICE HERE
const navigateAction = NavigationActions.navigate({
routeName: "preactivate",
params: {},
});
this.props.navigation.dispatch(navigateAction);
}}
style={styles.touchable}
>
<Text style={styles.btnlabel}>Register</Text>
</TouchableOpacity>
</View>
);
}
}
export default BankCustomerRegister;
when i click touchable.its supposed to navigate to otherPage, i'ts not navigating anywhere , even no errors.
myOtherPage(preactivate)
import React, { Component } from "react";
import {
View,
Text,
StyleSheet
} from "react-native";
class PreUserActivation extends Component {
// Render callBack
render() {
return (
<View style={styles.container}>
<Text>Screen</Text>
</View>
);
}
}
export default PreUserActivation;
My router config in router.js
//tab Router
export const Tab = TabNavigator(
{
BankCustomerRegister: {
screen: BankCustomerRegister,
navigationOptions: {
tabBarLabel: "Bank Customer"
}
},
nonbankcustomer: {
screen: NonCustomerRegister,
navigationOptions: {
tabBarLabel: "New Customer"
}
}
},
{
tabBarPosition: "top",
animationEnabled: true,
tabBarOptions: {
// activeTintColor: "#e91e63",
labelStyle: {
fontSize: 16
},
style: {
backgroundColor: "#08AE9E"
},
tabStyle: { width: 200 } //Set width to make INLINE TABS
}
}
);
export const Root = StackNavigator({
board: {
screen: OnBoardScreen,
navigationOptions: {
header: null
}
},
preactivate: {
screen: PreUserActivation,
navigationOptions: {
header: null
}
},
Tabs: {
screen: Tab
}
});
Is there something i'm missing.
You need a reset. Use navigate() when navigating from one tab to another in the same TabNavigator for example. In your case, you are navigating to a screen in the parent navigator. Try this instead:
onPress={() => {
const navigateAction = NavigationActions.reset({
index: 0,
actions: [
NavigationActions.navigate({ routeName: 'preactivate'})
]
});
this.props.navigation.dispatch(navigateAction);
}}

Resources